"""Product app back-office serializers."""
from django.utils.translation import gettext_lazy as _
from rest_framework import serializers

from gallery.models import Image
from product import models
from product.serializers import ProductDetailSerializer, ProductTypeBaseSerializer, \
                                ProductSubTypeBaseSerializer
from tag.models import TagCategory
from account.serializers.common import UserShortSerializer
from main.serializers import SiteSettingsSerializer

class ProductBackOfficeGallerySerializer(serializers.ModelSerializer):
    """Serializer class for model ProductGallery."""

    class Meta:
        """Meta class"""

        model = models.ProductGallery
        fields = [
            'id',
            'is_main',
        ]

    @property
    def request_kwargs(self):
        """Get url kwargs from request."""
        return self.context.get('request').parser_context.get('kwargs')

    def validate(self, attrs):
        """Override validate method."""
        product_pk = self.request_kwargs.get('pk')
        image_id = self.request_kwargs.get('image_id')

        product_qs = models.Product.objects.filter(pk=product_pk)
        image_qs = Image.objects.filter(id=image_id)

        if not product_qs.exists():
            raise serializers.ValidationError({'detail': _('Product not found')})

        if not image_qs.exists():
            raise serializers.ValidationError({'detail': _('Image not found')})

        product = product_qs.first()
        image = image_qs.first()

        if image in product.gallery.all():
            raise serializers.ValidationError({'detail': _('Image is already added.')})

        attrs['product'] = product
        attrs['image'] = image

        return attrs


class ProductBackOfficeDetailSerializer(ProductDetailSerializer):
    """Product back-office detail serializer."""
    in_favorites = serializers.BooleanField(allow_null=True, read_only=True)

    class Meta(ProductDetailSerializer.Meta):
        """Meta class."""
        fields = ProductDetailSerializer.Meta.fields + [
            'description',
            'available',
            'product_type',
            'establishment',
            # todo: need fix
            # 'wine_region',
            # 'wine_sub_region',
            'wine_village',
            'state',
            'site',
            'product_type'
        ]

class ProductTypeBackOfficeDetailSerializer(ProductTypeBaseSerializer):
    """Product type back-office detail serializer."""

    class Meta(ProductTypeBaseSerializer.Meta):
        """Meta class."""
        fields = ProductTypeBaseSerializer.Meta.fields + [
            'name',
            'use_subtypes',
        ]


class ProductTypeTagCategorySerializer(serializers.ModelSerializer):
    """Serializer for attaching tag category to product type."""
    product_type_id = serializers.PrimaryKeyRelatedField(
        queryset=models.ProductType.objects.all(),
        write_only=True)
    tag_category_id = serializers.PrimaryKeyRelatedField(
        queryset=TagCategory.objects.all(),
        write_only=True)

    class Meta(ProductTypeBaseSerializer.Meta):
        """Meta class."""
        fields = [
            'product_type_id',
            'tag_category_id',
        ]

    def validate(self, attrs):
        """Validation method."""
        product_type = attrs.pop('product_type_id')
        tag_category = attrs.get('tag_category_id')

        if tag_category in product_type.tag_categories.all():
            raise serializers.ValidationError({
                'detail': _('Tag category is already attached.')})

        attrs['product_type'] = product_type
        attrs['tag_category'] = tag_category
        return attrs

    def create(self, validated_data):
        """Overridden create method."""
        product_type = validated_data.get('product_type')
        tag_category = validated_data.get('tag_category')

        product_type.tag_categories.add(tag_category)
        return product_type


class ProductSubTypeBackOfficeDetailSerializer(ProductSubTypeBaseSerializer):
    """Product sub type back-office detail serializer."""

    class Meta(ProductSubTypeBaseSerializer.Meta):
        """Meta class."""
        fields = ProductSubTypeBaseSerializer.Meta.fields + [
            'product_type',
            'name',
            'index_name',
        ]


class ProductNoteBaseSerializer(serializers.ModelSerializer):
    """Serializer for model ProductNote."""

    user_detail = UserShortSerializer(read_only=True, source='user')

    class Meta:
        """Meta class."""
        model = models.ProductNote
        fields = [
            'id',
            'created',
            'modified',
            'text',
            'user',
            'user_detail',
            'product',
        ]
        extra_kwargs = {
            'created': {'read_only': True},
            'modified': {'read_only': True},
            'product': {'required': False, 'write_only': True},
            'user': {'required': False, 'write_only': True},
        }

    @property
    def serializer_view(self):
        """Return view instance."""
        return self.context.get('view')


class ProductNoteListCreateSerializer(ProductNoteBaseSerializer):
    """Serializer for List|Create action for model ProductNote."""

    def create(self, validated_data):
        """Overridden create method."""
        validated_data['user'] = self.user
        validated_data['product'] = self.product
        return super().create(validated_data)

    @property
    def user(self):
        """Return user instance from view."""
        if self.serializer_view:
            return self.serializer_view.request.user

    @property
    def product(self):
        """Return product instance from view."""
        if self.serializer_view:
            return self.serializer_view.get_object()
