# coding: utf-8

from procu.api import models
from procu.api.currency.serializers import CurrencyBriefSerializer
from procu.rest import serializers


class ProductsQueryParams(serializers.Serializer):
    currency = serializers.PKPrettyField(
        queryset=models.Currency.objects.filter(is_deleted=False),
        serializer=CurrencyBriefSerializer,
        allow_null=True,
        required=False,
    )


class Currency(CurrencyBriefSerializer):
    def to_representation(self, instance):
        query_params = self.context['view'].query_params
        currency = query_params.get('currency')
        return super().to_representation(currency or instance)


class OfferSerializer(serializers.ModelSerializer):
    quote = serializers.IntegerField(source='quote.id')
    supplier = serializers.CharField(source='quote.supplier.title')
    deadline_at = serializers.DateTimeField(source='quote.deadline_at')
    currency = Currency()
    value = serializers.CharField(source='formatted_value')

    class Meta:
        model = models.QuoteProduct
        fields = (
            'id',
            'quote',
            'supplier',
            'name',
            'is_replacement',
            'deadline_at',
            'value',
            'currency',
        )


class RequestSerializer(serializers.ModelSerializer):
    class Meta:
        model = models.Request
        fields = ('id', 'subject', 'created_at')


class ProductSerializer(serializers.ModelSerializer):
    offers = serializers.SerializerMethodField()
    enquiry = RequestSerializer(source='request.enquiry')

    class Meta:
        model = models.EnquiryProduct
        fields = ('id', 'name', 'enquiry', 'comment', 'offers')

    def get_offers(self, instance):
        offers = sorted(list(instance.offers), key=lambda x: x.value)
        return OfferSerializer(
            many=True, context=self.context
        ).to_representation(offers)
