# coding: utf-8

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


class CurrencyBriefSerializer(serializers.ModelSerializer):
    class Meta:
        model = models.Currency
        fields = ('id', 'prefix', 'suffix')


class QuoteProductSerializer(serializers.ModelSerializer):
    currency = CurrencyBriefSerializer()
    qty_expected = serializers.IntegerField(source='enquiry_product.qty')
    tax = serializers.DecimalField(
        max_digits=10, decimal_places=2, coerce_to_string=False
    )
    price_fmt = serializers.CharField(source='formatted_price')

    class Meta:
        model = models.QuoteProduct
        fields = (
            'id',
            'enquiry_product',
            'name',
            'qty',
            'qty_expected',
            'price',
            'price_fmt',
            'currency',
            'tax',
            'is_tax_included',
            'is_per_unit',
            'delivery_time',
            'comment',
            'is_replacement',
        )


class EnquiryProductSerializer(serializers.ModelSerializer):
    enquiry_product = serializers.IntegerField(source='id')
    offer = serializers.SerializerMethodField()
    replacements = QuoteProductSerializer(many=True)

    class Meta:
        model = models.EnquiryProduct
        fields = (
            'id',
            'enquiry_product',
            'name',
            'comment',
            'qty',
            'replacements',
            'offer',
        )

    def get_offer(self, instance):
        if instance.offers:
            return QuoteProductSerializer(
                instance.offers.pop(), context=self.context
            ).data
        return None


class Summary(serializers.Serializer):
    products = EnquiryProductSerializer(many=True)
