import datetime
from django.db import models
from django.conf import settings
from django.contrib.auth.models import Group
from django.utils import timezone
import uuid



from django.dispatch import receiver
from django.db.models.signals import pre_save


# Create your models here.
class cr_Category(models.Model):
    sName = models.CharField("Désignation", max_length=250)
    dtUpdated = models.DateTimeField('date updated', auto_now=True)
    dtCreated = models.DateTimeField('date published', auto_now_add=True)

    def __str__(self):
        return self.sName

    class Meta:
        verbose_name = "catégorie"
        verbose_name_plural = "catégories"

def increment_MessageId():
    last_id = cr_Message.objects.all().order_by('MessageId').last()
    if not last_id:
        return 1
    last_id = last_id.MessageId
    return last_id + 1

class cr_Message(models.Model):
    uuid = models.UUIDField(default=uuid.uuid4, editable=False, primary_key=True)
    MessageId = models.IntegerField("ID Message",editable=False, unique=True, default=increment_MessageId)
    Caterogy = models.ForeignKey(cr_Category, on_delete=models.DO_NOTHING, verbose_name="Catégorie")
    sDestUsers = models.TextField("Liste des utilisateurs cibles")
    sNotReadUsers = models.TextField()
    sReadedUsers = models.TextField("Liste des utilisateurs ayant lu", blank=True)
    DestGroup = models.ForeignKey(Group, on_delete=models.DO_NOTHING, verbose_name="Groupe de destination")
    sTitle = models.CharField("Titre", max_length=120)
    sText = models.TextField ("Corps de texte")
    dtValidityFrom = models.DateField("Validité depuis",default=timezone.now)
    dtValidityTo = models.DateField("Validité jusqu'à", blank=True, null=True)
    bEnabled = models.BooleanField("Actif", default=True)

    Author = models.ForeignKey(settings.AUTH_USER_MODEL, verbose_name="Auteur", on_delete=models.SET_NULL, null=True)
    sAuthor = models.CharField("Auteur", max_length=120)


    dtUpdated = models.DateTimeField('date updated', auto_now=True)
    dtCreated = models.DateTimeField('date published', auto_now_add=True)



    def get_dtCreated(self):
        return self.dtCreated.strftime("%d.%b.%Y %H:%M:%S")

    def calc_read_quotas(self):
        obj = self
        n_dest = obj.sDestUsers.count('[')
        n_readed = obj.sReadedUsers.count('[')

        if n_dest == 0:
            return "No dest"

        return f"{(n_readed/n_dest)*100}%"
    def __str__(self):
        return self.sTitle

    class Meta:
        verbose_name = "message"
        verbose_name_plural = "messages"

