# coding: utf-8

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


class QueryParamsSerializer(serializers.Serializer):
    tax = serializers.BooleanField(default=False)
    totals = serializers.BooleanField(default=False)
    rounded = serializers.BooleanField(default=False)
    currency = serializers.PrimaryKeyRelatedField(
        queryset=models.Currency.objects.filter(is_deleted=False), default=None
    )

    # Fixed parameters
    replacements = serializers.ReadOnlyField(default=True)


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
    )
    value = serializers.CharField(source='formatted_value')
    price_fmt = serializers.CharField(source='formatted_price')

    def to_representation(self, instance):
        data = super(QuoteProductSerializer, self).to_representation(instance)

        hidden = ('total', 'value', 'price', 'price_fmt')

        if not self.context['can_see_prices']:
            for key in hidden:
                data[key] = '****'

        currency = self.context.get('currency')

        if currency is not None:
            data['currency'] = currency

        return data

    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',
            'value',
            'approx',
            'total',
        )


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)
    currency = serializers.SerializerMethodField()

    def get_currency(self, instance):
        return self.context.get('currency')
