from django.db import models
from django.contrib.auth.models import User
from Sistemas.models import Sistema
from rest_framework.authtoken.models import Token

import re

class ClientesA24(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)
    class Meta:
        ordering = ('-Activo','RFC',)
    def __str__(self):
        return self.Nombre
    
class Sistemas_por_cliente_A24(models.Model):
    id_sistema= models.ForeignKey(Sistema, related_name='sistema_spc_IMMEX', on_delete=models.CASCADE)
    cliente   = models.ForeignKey(ClientesA24, related_name='cliente_spc_IMMEX', on_delete=models.CASCADE)
    num_licencias= models.IntegerField(default=1)
    def __str__(self):
        return f'{self.cliente.Nombre}'
    class Meta:
        ordering= ('-cliente','id_sistema')
        unique_together = ('id_sistema', 'cliente')

class DeviceA24(models.Model):
    clienteA24  = models.ForeignKey(ClientesA24,on_delete=models.CASCADE)
    deviceName  = models.CharField(max_length=255)
    deviceOS    = models.CharField(max_length=255)
    deviceIP    = models.GenericIPAddressField()
    token       = models.ForeignKey(Token, on_delete=models.CASCADE,to_field='key', max_length=40,  blank=True,null=True)
    username    = models.ForeignKey(User, on_delete=models.CASCADE)
    sistema     = models.ForeignKey(Sistema, on_delete=models.CASCADE)
    MAC         = models.CharField(max_length=30, blank=True, null=True)
    dataBase    = models.CharField(max_length=40, blank=True,null=True)
    timestamp   = models.DateTimeField(auto_now_add=True)

    class Meta:
        ordering = ('username',)
        

    def generate_username(self):
        """"""
        username_ = f"SCAII_{self.clienteA24}_{self.deviceName}_{self.MAC}"
        username_ = re.sub(r'\W+', '', username_)

        if User.objects.filter(username=username_).exists():
            return User.objects.get(username=username_)
        return User.objects.create_user(username=username_)

    def save(self,*args, **kwargs):
        """Overrides save method"""
        if not self.pk:
            obj = self.generate_username()
            self.username=obj
            token, created = Token.objects.get_or_create(user=obj)

            self.token = token
            super().save(*args, **kwargs)

    def __str__(self):
        return f'{self.username}'