# -*- coding: utf-8 -*-
from django.conf import settings
from django.core.exceptions import ValidationError
from django.utils.translation import ugettext as _
from django.contrib.contenttypes.models import ContentType
from django.contrib.auth.models import Permission


def pre_delete_group(sender, instance, *args, **kwargs):
    if instance.pk in settings.GROUP_IDS.values():
        raise ValidationError(_('cant_delete_this_group_message'))  # нельзя удалять эту группу


def update_permissions_after_migration(sender, **kwargs):
    from django.conf import settings
    from django.contrib.auth.management import create_permissions

    create_permissions(sender, verbosity=2 if settings.DEBUG else 0)


def add_full_permissions(sender, **kwargs):
    for content_type in ContentType.objects.filter(app_label=sender.label):
        model = content_type.model_class()
        if model and model._meta.proxy:
            continue
        for codename in ['view_%s', 'change_%s']:
            codename = codename % content_type.model
            if not Permission.objects.filter(content_type=content_type, codename=codename):
                Permission.objects.create(content_type=content_type, codename=codename, name="%s" % codename[:50])


def update_contenttypes_names(**kwargs):
    for content_type in ContentType.objects.all():
        model_class = content_type.model_class()
        if model_class:
            new_name = model_class._meta.verbose_name
            if content_type.name != new_name:
                content_type.name = new_name
                content_type.save()
