from django.db import models
import datetime

from django.db.models import Q


class saldoModel(models.Model):
    saldo = models.IntegerField()


class Timbres(models.Model):
    uuid = models.CharField(max_length=37, unique=True)
    rfcc = models.CharField(max_length=13,db_index=True)
    rfcp = models.CharField(max_length=13)
    fecha = models.CharField(max_length=55)
    folio = models.CharField(max_length=55)
    serie = models.CharField(max_length=10,blank=True)
    tipo  = models.CharField(max_length=35)

    created_at = models.DateTimeField(auto_now_add=True)
    modo = models.CharField(max_length=10,blank=True, null =True)
    class Meta:
        ordering = ('-created_at',)


class ErroresTimbres(models.Model):
    uuid = models.CharField(max_length=36)
    description = models.TextField()
    rfcc = models.CharField(max_length=13)
    folio = models.CharField(max_length=55)

    created_at = models.DateTimeField(auto_now_add=True)
    modo = models.CharField(max_length=10,blank=True, null =True)
    class Meta:
        ordering = ('uuid',)
        
        
class Clientes(models.Model):
    RFC = models.CharField(max_length=13, unique=True)
    Nombre = models.CharField(max_length=100)
    Activo = models.BooleanField(default=False)
    fecha_baja = models.DateField(blank=True,null=True)
    email = models.EmailField(max_length=254, blank=True)
    conteo_mes = models.IntegerField(blank=True,null=True,default=0)
    def timbres_X_MES(self, mes=None, year=None, PAC=None):
        today = datetime.date.today()
        if year is None:
            year  = today.year        
        if mes==None:
            mes = today.month
        
        dat = datetime.datetime(int(year),int(mes),1)
        if dat.month in (1,3,5,7,8,10,12):#31    
            findate = dat  + datetime.timedelta(days=30)

        elif dat.month in (4,6,9,11):#30
            findate = dat  + datetime.timedelta(days=29)

        else:#28 or 29
            findate = dat  + datetime.timedelta(days=28)
        findate += datetime.timedelta(days=1)

        filter_q = Q(rfcc=self.RFC) & Q(created_at__range=[dat,findate])
        if PAC:
            filter_q &=Q(rfcp=PAC)
        cou = Timbres.objects.filter(filter_q).count()
        # if PAC:
        #     cou = Timbres.objects.filter(rfcc=self.RFC, created_at__range=[dat,findate], rfcp=PAC).count()
        # else:
        #     cou = Timbres.objects.filter(rfcc=self.RFC, created_at__range=[dat,findate]).count()
        self.conteo_mes =cou
        self.save()
        
    @property
    def timbres_mes_count(self):
        today = datetime.date.today()
        month = today.month
        year  = today.year
        return Timbres.objects.filter(rfcc=self.RFC, created_at__year=str(year),created_at__month=str(month)).count()
    class Meta:
        ordering = ('-Activo','-conteo_mes','RFC',)
    
    def __str__(self):
        return self.Nombre

