
from rest_framework import serializers
from .models import Device, Sistema, sistemas_por_cliente
from Clientes.models import Clientes
from django.db.models import Q

class SistemaPrimaryKeyRelatedField(serializers.PrimaryKeyRelatedField):
    def to_internal_value(self,data):
        try:            
            return Sistema.objects.get(nombre_sistema=data)
        except Sistema.DoesNotExist:
            raise serializers.ValidationError("Sistema no existe")

class ClientPrimaryKeyRelatedField(serializers.PrimaryKeyRelatedField):
    def to_internal_value(self,data):
        try:
            return Clientes.objects.get(RFC=data)
        except Clientes.DoesNotExist:
            raise serializers.ValidationError("No existe Cliente")

class DeviceSerializer(serializers.ModelSerializer):
    client = ClientPrimaryKeyRelatedField(queryset=Clientes.objects.all())    
    sistema = SistemaPrimaryKeyRelatedField(queryset=Sistema.objects.all())
    
    #this read_only fields not are required to be updated in the serializer.
    #however in the model are required in other instantiation like queries, forms, are required to add it    
    token = serializers.CharField(read_only=True)
    macAddress = serializers.CharField(read_only=True)
    class Meta:
        model =Device
        fields = ('client','sistema','device_name','device_os', 'ip_address','token', 'macAddress', 'database',)

    #this assign the masAddress value from
    #the request context passed throught argument in the view to the serializer
    #given that the macAddres field are read_Only in the beggining of this serialazer
    #we need passing the post data to the creation instance before commited to the DB
    def create(self, validated_data):
        mac_address = self.context['request'].data.get('macAddress')
        # sistema = validated_data['sistema']
        # client = validated_data['client']
        # existing_devices = Device.objects.filter(
        #     Q(sistema=sistema)
        #     & Q(client=client)
        #     & Q(macAddress__icontains=mac_address)
        #     & Q(database=self.context['request'].data.get('database'))
        # )
        # print('self.context[request].data',self.context['request'].data)
        # if existing_devices.exists():
        #     # A device with the same macAddress already exists for the given sistema and client
        #     # Get the number of existing devices and add 1 to create a new suffix
        #     suffix = existing_devices.count() + 1
        #     mac_address += f'_{suffix}'

        validated_data['macAddress']= mac_address
        return super().create(validated_data)
    
    def validate(self, data):
        sistema = data.get('sistema', None)
        client = data.get('client', None)
        
        try:
            sistemaxCli =  sistemas_por_cliente.objects.get(id_sistema=sistema,cliente=client)
        except sistemas_por_cliente.DoesNotExist:
            raise serializers.ValidationError('No existe licencia para este sistema y/o cliente')
        if sistemaxCli.num_licencias <= Device.objects.filter(sistema=sistemaxCli.id_sistema, client=client).count():
            raise serializers.ValidationError(f"No hay licencias disponibles para este sistema:{sistema} y cliente:{client}")
        return data