from apps.authentication.api.v1.serializers.serializer import BankAccountSerializer
from apps.pos_device.web.api.v1.serilaizers import client as client_serializer
from rest_framework.serializers import ModelSerializer
from apps.pos_device import models as pos_models
from rest_framework.exceptions import APIException
from apps.pos_device import exceptions as pos_exceptions
from rest_framework import status


class ProviderCompanySerializer(ModelSerializer):
    class Meta:
        model = pos_models.ProviderCompany
        fields = '__all__'


class DeviceSerializer(ModelSerializer):
    class Meta:
        model = pos_models.Device
        fields = '__all__'

    def to_representation(self, instance):
        """ custom output of serializer """
        representation = super().to_representation(instance)

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

        representation['assignment'] = DeviceAssignmentSerializer(
            instance.assignment.all().first()
        ).data

        return representation


class DeviceVersionSerializer(ModelSerializer):
    class Meta:
        model = pos_models.DeviceVersion
        fields = '__all__'


class SessionSerializer(ModelSerializer):
    class Meta:
        model = pos_models.Sessions
        fields = '__all__'


class DeviceAssignmentSerializer(ModelSerializer):
    class Meta:
        model = pos_models.DeviceAssignment
        fields = '__all__'

    def validate(self, attrs):

        device = attrs['device']
        client = attrs['client']

        if not self.instance:
            if self.Meta.model.objects.filter(device=device, client=client).exists():
                raise pos_exceptions.DeviceAlreadyAssigned()

        return attrs

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

        representation['client'] = client_serializer.POSClientSerializer(
            instance.client
        ).data

        return representation


class StakeHoldersSerializer(ModelSerializer):
    class Meta:
        model = pos_models.StakeHolders
        fields = '__all__'

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

        representation['bank_account'] = BankAccountSerializer(
            instance.organization.bank_information.all().first()
        ).data

        return representation


class BrokerStakeHolderAssignSerializer(ModelSerializer):
    class Meta:
        model = pos_models.BrokerStakeHolderAssignment
        fields = '__all__'
