# -*- mode: python; coding: utf-8 -*-
# Copyright (C) 2017-2019 by BDE ENS Paris-Saclay
# SPDX-License-Identifier: GPL-3.0-or-later

import datetime
import uuid

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

from med.settings import MAX_EMPRUNT, REQ_EXPIRE_HRS


class User(AbstractUser):
    telephone = models.CharField(
        verbose_name=_('phone number'),
        max_length=15,
        null=True,
        blank=True,
    )
    address = models.CharField(
        verbose_name=_('address'),
        max_length=255,
        null=True,
        blank=True,
    )
    maxemprunt = models.IntegerField(
        verbose_name=_('maximum borrowed'),
        help_text=_('Maximal amount of simultaneous borrowed item authorized.'),
        default=MAX_EMPRUNT,
    )
    comment = models.CharField(
        verbose_name=_('comment'),
        help_text=_('Promotion...'),
        max_length=255,
        blank=True,
    )

    REQUIRED_FIELDS = ['first_name', 'last_name', 'email']

    def has_perms(self, perms, obj=None):
        for perm in perms:
            try:
                Right.objects.get(user=self, right__listright=perm)
                return True
            except Right.DoesNotExist:
                return False

    def has_perm(self, perm, obj=None):
        return True

    def has_right(self, right):
        return Right.objects.filter(user=self).filter(right=ListRight.objects.get(listright=right)).exists()

    def has_module_perms(self, app_label):
        # Simplest version again
        return True

    @property
    def is_adherent(self):
        last_adh_year = Adhesion.objects.all().order_by('annee_debut').reverse().first()
        return last_adh_year and self in last_adh_year.adherent.all()


class Request(models.Model):
    PASSWD = 'PW'
    EMAIL = 'EM'
    TYPE_CHOICES = (
        (PASSWD, 'Mot de passe'),
        (EMAIL, 'Email'),
    )
    type = models.CharField(max_length=2, choices=TYPE_CHOICES)
    token = models.CharField(max_length=32)
    user = models.ForeignKey('User', on_delete=models.PROTECT)
    created_at = models.DateTimeField(auto_now_add=True, editable=False)
    expires_at = models.DateTimeField()

    def save(self):
        if not self.expires_at:
            self.expires_at = timezone.now() \
                              + datetime.timedelta(hours=REQ_EXPIRE_HRS)
        if not self.token:
            self.token = str(uuid.uuid4()).replace('-', '')  # remove hyphens
        super().save()


class Right(models.Model):
    PRETTY_NAME = "Droits affectés à des users"

    user = models.ForeignKey('User', on_delete=models.PROTECT)
    right = models.ForeignKey('ListRight', on_delete=models.PROTECT)

    class Meta:
        verbose_name = _("right")
        verbose_name_plural = _("rights")
        unique_together = ("user", "right")

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


class ListRight(models.Model):
    PRETTY_NAME = "Liste des droits existants"

    listright = models.CharField(max_length=255, unique=True)
    details = models.CharField(help_text="Description", max_length=255, blank=True)

    def __str__(self):
        return self.listright


class Clef(models.Model):
    nom = models.CharField(max_length=255, unique=True)
    proprio = models.ForeignKey('User', on_delete=models.PROTECT, blank=True, null=True)
    commentaire = models.CharField(max_length=255, null=True, blank=True)


class Adhesion(models.Model):
    annee_debut = models.IntegerField(unique=True)
    annee_fin = models.IntegerField(unique=True)
    adherent = models.ManyToManyField('User', blank=True)
