from rest_framework.serializers import ModelSerializer
from apps.pos_device import models as pos_models
from rest_framework.exceptions import APIException
from rest_framework import status


class POSClientSerializer(ModelSerializer):
    class Meta:
        model = pos_models.POSClient
        fields = '__all__'

    def validate(self, attrs):
        org = attrs['organization']

        # check for duplicate organization client
        if not self.instance and org:
            if self.Meta.model.objects.filter(organization=org).exists():
                raise APIException("قبلا کلاینت با این سازمان ثبت شده است", code=status.HTTP_403_FORBIDDEN)  # noqa

        return attrs

    def to_representation(self, instance):
        representation = super().to_representation(instance)

        representation['organization'] = {
            'name': instance.organization.name,
            'id': instance.organization.id
        }

        return representation


class POSClientAttributeSerializer(ModelSerializer):
    class Meta:
        model = pos_models.POSClientAttribute
        fields = '__all__'


class POSClientAttributeValueSerializer(ModelSerializer):
    class Meta:
        model = pos_models.POSClientAttributeValue
        fields = '__all__'
