# coding: utf-8

from django.utils.translation import gettext_lazy as _

from procu.api import models
from procu.api.supplier.serializers import Info, SupplierTagBriefSerializer
from procu.api.supplier.validators import validate_vat_id
from procu.rest import serializers


class Retrieve(serializers.ModelSerializer):
    tags = serializers.SerializerMethodField(label=_('SUPPLIER_ACCOUNT::TAGS'))
    info = Info(required=False, label=_('SUPPLIER_ACCOUNT::INFO'))

    class Meta:
        model = models.Supplier
        fields = ('id', 'tags', 'legal_name', 'vat_id', 'info')

    @staticmethod
    def get_tags(instance):
        tags = instance.tags.filter(is_hidden=False)
        return SupplierTagBriefSerializer(tags, many=True).data


class Update(serializers.ModelSerializer):
    check_for_nested_writes = False

    tags = serializers.PrimaryKeyRelatedField(
        queryset=models.SupplierTag.objects.filter(is_hidden=False),
        many=True,
        allow_empty=True,
        required=False,
        label=_('SUPPLIER_ACCOUNT::TAGS'),
    )
    info = Info(required=False, label=_('SUPPLIER_ACCOUNT::INFO'))

    vat_id = serializers.CharField(
        required=True,
        allow_blank=True,
        validators=[validate_vat_id],
        max_length=255,
    )

    class Meta:
        model = models.Supplier
        fields = ('tags', 'legal_name', 'vat_id', 'info')

    def validate_tags(self, data):
        hidden_tags = list(self.instance.tags.filter(is_hidden=True))
        return data + hidden_tags
