from django.contrib.auth.models import Group, Permission
from django.db import models
from django.utils.crypto import get_random_string
from django.utils.translation import gettext_lazy as _

KFET_APP_LABELS = ["kfet", "kfetauth"]


class GenericTeamTokenManager(models.Manager):
    def create_token(self):
        token = get_random_string(50)
        while self.filter(token=token).exists():
            token = get_random_string(50)
        return self.create(token=token)


class GenericTeamToken(models.Model):
    token = models.CharField(max_length=50, unique=True)

    objects = GenericTeamTokenManager()


class KFetPermissionManager(models.Manager):
    def get_queryset(self):
        return (
            super().get_queryset().filter(content_type__app_label__in=KFET_APP_LABELS)
        )


class KFetPermission(Permission):
    objects = KFetPermissionManager()

    class Meta:
        proxy = True
        verbose_name = _("Permission K-Fêt")
        verbose_name_plural = _("Permissions K-Fêt")


class KFetGroup(Group):
    # On fait un héritage complet pour
    # mieux distinguer les groupes K-Fêt via l'ORM (i.e. faire `KFetGroup.objects.all`)

    class Meta:
        verbose_name = _("Groupe K-Fêt")
        verbose_name_plural = _("Groupes K-Fêt")
