from django.apps import AppConfig, apps as global_apps
from django.db.models import Q
from django.db.models.signals import post_migrate


def bds_group_perms(app_config, apps=global_apps, **kwargs):
    try:
        Permission = apps.get_model("auth", "Permission")
        Group = apps.get_model("auth", "Group")

        group = Group.objects.get(name="Burô du BDS")
        perms = Permission.objects.filter(
            Q(content_type__app_label="bds")
            | Q(content_type__app_label="auth") & Q(content_type__model="user")
        )
        group.permissions.set(perms)
        group.save()

    except (LookupError, Group.DoesNotExist):
        return


class BdsConfig(AppConfig):
    name = "bds"
    verbose_name = "Gestion des adhérent·e·s du BDS"

    def ready(self):
        post_migrate.connect(bds_group_perms, sender=self)
