from apps.authentication.api.v1.serializers.serializer import OrganizationSerializer
from apps.authorization.api.v1 import serializers as authorize_serializers
from apps.product.web.api.v1.serializers import product_serializers
from apps.livestock.web.api.v1.serializers import LiveStockTypeSerializer
from apps.product import models as product_models
from rest_framework import serializers


class QuotaSerializer(serializers.ModelSerializer):
    class Meta:
        model = product_models.Quota
        fields = '__all__'

    def to_representation(self, instance):
        representation = super().to_representation(instance)
        if isinstance(instance, product_models.Quota):
            if instance.sale_unit:
                representation['sale_unit'] = product_serializers.SaleUnitSerializer(
                    instance.sale_unit
                ).data
            representation['product'] = {"product": instance.product.name, "product_id": instance.product.id}
            representation['incentive_plan'] = QuotaIncentiveAssignmentSerializer(
                instance.incentive_assignments.all(),
                many=True
            ).data

            representation['attribute_values'] = product_serializers.AttributeValueSerializer(
                instance.attribute_values.all(),
                many=True
            ).data

            representation['brokers'] = QuotaBrokerValueSerializer(
                instance.broker_values.all(),
                many=True
            ).data

            representation['livestock_allocations'] = QuotaLiveStockAllocationSerializer(
                instance.livestock_allocations.all(),
                many=True
            ).data

            representation['livestock_limitations'] = QuotaLiveStockAgeLimitationSerializer(
                instance.livestock_age_limitations.all(),
                many=True
            ).data

            representation['limit_by_organizations'] = [
                {"name": limit.name, "id": limit.id} for limit in instance.limit_by_organizations.all()
            ]

        return representation

    def update(self, instance, validated_data):
        """ Custom Update """

        instance.quota_id = validated_data.get('quota_id', instance.quota_id)
        instance.quota_code = validated_data.get('quota_code', instance.quota_code)
        instance.quota_weight = validated_data.get('quota_weight', instance.quota_weight)
        instance.remaining_weight = validated_data.get('remaining_weight', instance.remaining_weight)
        instance.quota_distributed = validated_data.get('quota_distributed', instance.quota_distributed)
        instance.product = validated_data.get('product', instance.product)
        instance.sale_type = validated_data.get('sale_type', instance.sale_type)
        instance.sale_unit = validated_data.get('sale_unit', instance.sale_type)
        instance.month_choices = validated_data.get('month_choices', instance.month_choices)
        instance.sale_license = validated_data.get('sale_license', instance.sale_license)
        instance.group = validated_data.get('group', instance.group)
        instance.has_distribution_limit = validated_data.get('has_distribution_limit', instance.has_distribution_limit)
        instance.distribution_mode = validated_data.get('distribution_mode', instance.distribution_mode)
        instance.has_organization_limit = validated_data.get('has_organization_limit', instance.has_organization_limit)
        instance.base_price_factory = validated_data.get('base_price_factory', instance.base_price_factory)
        instance.base_price_cooperative = validated_data.get('base_price_cooperative', instance.base_price_cooperative)
        instance.final_price = validated_data.get('final_price', instance.final_price)
        instance.is_closed = validated_data.get('is_closed', instance.is_closed)
        instance.closed_at = validated_data.get('closed_at', instance.closed_at)
        instance.save()

        # update assigned organization many to many
        if 'assigned_organizations' in validated_data.keys():
            instance.assigned_organizations.clear()
            instance.assigned_organizations.add(
                *(validated_data.get('assigned_organizations', instance.assigned_organizations))
            )

        # update organization limit many to many
        if 'limit_by_organizations' in validated_data.keys():
            instance.limit_by_organizations.clear()
            instance.limit_by_organizations.add(
                *(validated_data.get('limit_by_organizations', instance.limit_by_organizations))
            )
        else:
            instance.limit_by_organizations.clear()

        return instance


class QuotaStatsSerializer(serializers.ModelSerializer):
    class Meta:
        model = product_models.QuotaStats
        fields = '__all__'


class QuotaIncentiveAssignmentSerializer(serializers.ModelSerializer):
    class Meta:
        model = product_models.QuotaIncentiveAssignment
        fields = [
            "id",
            "quota",
            "incentive_plan",
            "heavy_value",
            "light_value",
        ]

    def to_representation(self, instance):
        """ Custom Output for incentive plans """

        representation = super().to_representation(instance)
        representation['incentive_plan_name'] = instance.incentive_plan.name

        return representation

    def update(self, instance, validated_data):
        """ Custom Update """

        instance.quota = validated_data.get('quota', instance.quota)
        instance.incentive_plan = validated_data.get('incentive_plan', instance.incentive_plan)
        instance.heavy_value = validated_data.get('heavy_value', instance.heavy_value)
        instance.light_value = validated_data.get('light_value', instance.light_value)
        instance.save()

        return instance


class QuotaBrokerValueSerializer(serializers.ModelSerializer):  # noqa
    class Meta:
        model = product_models.QuotaBrokerValue
        fields = [
            "id",
            "quota",
            "broker",
            "value",
        ]

    def to_representation(self, instance):
        """ Custom Output of broker values """

        representation = super().to_representation(instance)
        representation['broker_name'] = instance.broker.name

        return representation

    def update(self, instance, validated_data):
        """ Custom Update """

        instance.quota = validated_data.get('quota', instance.quota)
        instance.broker = validated_data.get('broker', instance.broker)
        instance.value = validated_data.get('value', instance.value)
        instance.save()

        return instance


class QuotaLiveStockAllocationSerializer(serializers.ModelSerializer):
    class Meta:
        model = product_models.QuotaLivestockAllocation
        fields = [
            "id",
            "quota",
            "livestock_group",
            "livestock_type",
            "livestock_subtype",
            "quantity_kg",
        ]
        extra_kwargs = {
            'livestock_group': {
                'required': False
            },
            'livestock_type': {
                'required': False
            },
            'livestock_subtype': {
                'required': False
            }
        }

    def to_representation(self, instance):
        """ custom output for live stock type """

        representation = super().to_representation(instance)
        if isinstance(instance, product_models.QuotaLivestockAllocation):
            representation['livestock_type'] = LiveStockTypeSerializer(instance.livestock_type).data

        return representation

    def update(self, instance, validated_data):
        """ Custom Update """

        instance.quota = validated_data.get('quota', instance.quota)
        instance.livestock_group = validated_data.get('livestock_group', instance.livestock_group)
        instance.livestock_type = validated_data.get('livestock_type', instance.livestock_type)
        instance.livestock_subtype = validated_data.get('livestock_subtype', instance.livestock_subtype)
        instance.save()

        return instance


class QuotaLiveStockAgeLimitationSerializer(serializers.ModelSerializer):
    class Meta:
        model = product_models.QuotaLiveStockAgeLimitation
        fields = [
            "id",
            "quota",
            "livestock_type",
            "livestock_subtype",
            "age_month",
        ]

    def to_representation(self, instance):
        """ custom output for livestock type """

        representation = super().to_representation(instance)
        if isinstance(instance, product_models.QuotaLiveStockAgeLimitation):
            representation['livestock_type'] = LiveStockTypeSerializer(
                instance.livestock_type
            ).data

        return representation

    def update(self, instance, validated_data):
        """ Custom Update """

        instance.quota = validated_data.get('quota', instance.quota)
        instance.livestock_type = validated_data.get('livestock_type', instance.livestock_type)
        instance.livestock_subtype = validated_data.get('livestock_subtype', instance.livestock_subtype)
        instance.age_month = validated_data.get('age_month', instance.age_month)
        instance.save()

        return instance
