from datetime import date
from os.path import splitext

from django.contrib.auth import get_user_model
from django.db import models
from django.utils import timezone
from django.utils.translation import gettext_lazy as _

from shared.utils import choices_length

User = get_user_model()


class BDSProfile(models.Model):
    OCCUPATION_CHOICES = (
        ("EXT", "Extérieur"),
        ("1A", "1A"),
        ("2A", "2A"),
        ("3A", "3A"),
        ("4A", "4A"),
        ("MAG", "Magistérien"),
        ("ARC", "Archicube"),
        ("DOC", "Doctorant"),
        ("CST", "CST"),
        ("PER", "Personnel ENS"),
    )

    TYPE_COTIZ_CHOICES = (
        ("ETU", "Étudiant"),
        ("NOR", "Normalien"),
        ("EXT", "Extérieur"),
        ("ARC", "Archicube"),
    )

    COTIZ_DURATION_CHOICES = (
        ("ANN", "Année"),
        ("SE1", "Premier semestre"),
        ("SE2", "Deuxième semestre"),
        ("NO", "Aucune"),
    )

    def get_certificate_filename(instance, filename):
        _, ext = splitext(filename)  # récupère l'extension du fichier
        year = str(date.now().year)
        return "certifs/{username}-{year}.{ext}".format(
            username=instance.user.username, year=year, ext=ext
        )

    user = models.OneToOneField(User, on_delete=models.CASCADE, related_name="bds")
    phone = models.CharField(_("téléphone"), max_length=20, blank=True)
    occupation = models.CharField(
        _("occupation"),
        default="1A",
        choices=OCCUPATION_CHOICES,
        max_length=choices_length(OCCUPATION_CHOICES),
    )
    departement = models.CharField(_("département"), max_length=50, blank=True)
    birthdate = models.DateField(
        auto_now_add=False,
        auto_now=False,
        verbose_name=_("date de naissance"),
        blank=True,
        null=True,
    )

    is_member = models.BooleanField(_("adhérent⋅e du BDS"), default=False)

    mails_bds = models.BooleanField(_("recevoir les mails du BDS"), default=False)

    has_certificate = models.BooleanField(_("certificat médical"), default=False)

    ASPSL_number = models.CharField(
        _("numéro AS PSL"), max_length=50, blank=True, null=True
    )
    FFSU_number = models.CharField(
        _("numéro FFSU"), max_length=50, blank=True, null=True
    )
    cotisation_period = models.CharField(
        _("inscription"), default="NO", choices=COTIZ_DURATION_CHOICES, max_length=3
    )
    registration_date = models.DateField(
        auto_now_add=True, verbose_name=_("date d'inscription")
    )
    cotisation_type = models.CharField(
        _("type de cotisation"), choices=TYPE_COTIZ_CHOICES, max_length=9
    )

    comments = models.TextField(
        _("commentaires"),
        blank=True,
        help_text=_(
            "Attention : l'utilisateur·ice dispose d'un droit d'accès aux données "
            "le/la concernant, dont le contenu de ce champ !"
        ),
    )

    @classmethod
    def expired_members(cls):
        now = timezone.now()
        qs = cls.objects.filter(is_member=True)
        if now.month > 1 and now.month < 7:
            return qs.filter(cotisation_period="SE1")
        elif now.month < 2 or now.month > 8:
            return qs.none()
        return qs

    class Meta:
        verbose_name = _("Profil BDS")
        verbose_name_plural = _("Profils BDS")
        permissions = (("is_team", _("est membre du burô")),)

    def __str__(self):
        return self.user.username
