from rest_framework import serializers
from apps.product import models as product_models
from apps.product.web.api.v1.serializers.quota_serializers import QuotaSerializer
from django.db import models
from apps.product.exceptions import (
    QuotaWeightException,
    QuotaClosedException,
    QuotaExpiredTimeException
)


class QuotaDistributionSerializer(serializers.ModelSerializer):
    class Meta:
        model = product_models.QuotaDistribution
        fields = '__all__'
        extra_kwargs = {
            'assigner_organization': {
                'required': False
            }
        }

    def validate(self, data):
        """
        to validate if distribution weight
        more than quota weight raise exception
        or if quota is closed raise exception
        """

        quota = data['quota']
        amount = data['weight']
        instance_id = self.instance.id if self.instance else None

        # check quota expired time
        if not quota.is_in_valid_time():
            raise QuotaExpiredTimeException()

        # check if quota is closed
        if quota.is_closed:
            raise QuotaClosedException()

        # total quota distributions weight
        total = product_models.QuotaDistribution.objects.filter(
            quota=quota
        ).exclude(id=instance_id).aggregate(
            total=models.Sum('weight')
        )['total'] or 0
        if total + amount > quota.quota_weight:
            raise QuotaWeightException()

        return data

    def to_representation(self, instance):
        """ Custom output of serializer """

        representation = super().to_representation(instance)
        if instance.quota:
            representation['quota'] = QuotaSerializer(instance.quota).data

        return representation
