# coding: utf-8

from django.utils import timezone
from django.utils.translation import gettext_lazy as _
from rest_framework.exceptions import ValidationError

from procu.api import enums, models
from procu.rest import serializers
from ..fields import Fields, Product as InitialProduct
from ..request.serializers import Product as EnquiryProduct


class RequestPrepare(serializers.ModelSerializer):
    check_for_nested_writes = False

    description = serializers.CharField(source='internal_comment')
    products = InitialProduct(many=True, source='initial_products')
    attachments = Fields.attachments()

    def to_representation(self, instance):
        response = super().to_representation(instance)
        response.update(instance.extra)
        return response

    class Meta:
        model = models.Enquiry
        fields = (
            'subject',
            'products',
            'description',
            'no_replacement',
            'address',
            'legal_entity',
            'attachments',
        )


class SupplierBrief(serializers.ModelSerializer):
    class Meta:
        model = models.Supplier
        fields = ('id', 'title', 'legal_name', 'is_cold', 'is_deleted')


class RequestCreate(serializers.ModelSerializer):
    check_for_nested_writes = False

    address = Fields.address(allow_null=False)
    legal_entity = Fields.legal_entity(allow_null=False)
    attachments = Fields.attachments()

    products = EnquiryProduct(
        label=_('ENQUIRIES::PRODUCTS'), allow_empty=False, many=True
    )

    suppliers = serializers.PKPrettyField(
        queryset=models.Supplier.objects.filter(is_deleted=False),
        serializer=SupplierBrief,
        allow_empty=False,
        label=_('QUOTES::SUPPLIERS'),
        many=True,
    )

    class Meta:
        model = models.Request
        fields = (
            'subject',
            'products',
            'description',
            'no_replacement',
            'deadline_at',
            'address',
            'legal_entity',
            'attachments',
            'suppliers',
            'show_assignee',
        )
        extra_kwargs = {
            'subject': {'max_length': 512},
            'deadline_at': {'allow_null': False},
        }

    @staticmethod
    def validate_deadline_at(value):
        if value < timezone.now():
            raise ValidationError(_('ENQUIRIES::ERROR_PUBLISH_LATE'))
        return value

    def create(self, data):
        attachments = data.pop('attachments', None)
        suppliers = data.pop('suppliers', None)
        products = data.pop('products', None)

        instance = super().create(data)

        if attachments is not None:

            for attachment in attachments:
                if attachment.enquiry_id not in (instance.enquiry_id, None):
                    continue

                attachment.request_id = instance.id
                attachment.save()

        if products is not None:
            objs = []

            for product in products:
                product['request_id'] = instance.id
                objs.append(models.EnquiryProduct(**product))

            models.EnquiryProduct.objects.bulk_create(objs)

        if suppliers is not None:
            objs = []

            for supplier in suppliers:
                objs.append(
                    models.Quote(
                        supplier=supplier,
                        request_id=instance.id,
                        terms=supplier.terms,
                        deadline_at=instance.deadline_at,
                        status=enums.QS.BIDDING,
                    )
                )
            models.Quote.objects.bulk_create(objs)

        return instance


class Log(serializers.Serializer):

    legal_entity = Fields.legal_entity()
    address = Fields.address()
    attachments = Fields.attachments()
    deadline_at = Fields.deadline_at(format=None)
    no_replacement = serializers.BooleanField()
    description = serializers.CharField()
    subject = serializers.CharField()

    class Meta:
        fields = (
            'id',
            'subject',
            'attachments',
            'deadline_at',
            'no_replacement',
            'description',
            'legal_entity',
            'address',
            'deadline_at',
            'no_replacement',
            'description',
            'attachments',
        )
