from django.conf import settings
from django.utils.text import slugify
from rest_framework import serializers

from tag.models import Tag
from translation.models import SiteInterfaceDictionary
from transfer.mixins import TransferSerializerMixin
from transfer.models import Cepages


class AssemblageTagSerializer(TransferSerializerMixin):

    CATEGORY_LABEL = 'Grape variety'
    CATEGORY_INDEX_NAME = slugify(CATEGORY_LABEL)

    percent = serializers.FloatField()
    cepage_id = serializers.PrimaryKeyRelatedField(
        queryset=Cepages.objects.all())

    class Meta:
        model = Tag
        fields = (
            'percent',
            'cepage_id',
        )

    def validate(self, attrs):
        percent = attrs.pop('percent')
        cepage = attrs.pop('cepage_id')
        value = self.get_tag_value(cepage, percent)

        attrs['label'] = {settings.FALLBACK_LOCALE: value}
        attrs['value'] = slugify(value)
        attrs['category'] = self.tag_category
        return attrs

    def create(self, validated_data):
        qs = self.Meta.model.objects.filter(**validated_data)
        category = validated_data.get('category')
        translations = validated_data.pop('label')
        if not qs.exists() and category:
            instance = super().create(validated_data)
            SiteInterfaceDictionary.objects.update_or_create_for_tag(instance, translations)
            return instance

    def get_tag_value(self, cepage, percent):
        if cepage and percent:
            return f'{cepage.name} - {percent}%'


class CepageTagSerializer(TransferSerializerMixin):

    CATEGORY_LABEL = 'Cepage'
    CATEGORY_INDEX_NAME = slugify(CATEGORY_LABEL)

    name = serializers.CharField()

    class Meta:
        model = Tag
        fields = (
            'name',
        )

    def validate(self, attrs):

        name = attrs.pop('name')

        attrs['label'] = {settings.FALLBACK_LOCALE: name}
        attrs['value'] = slugify(name)
        attrs['category'] = self.tag_category
        return attrs
