from location import models
from location.serializers import common
from rest_framework import serializers
from gallery.models import Image
from django.utils.translation import gettext_lazy as _


class AddressCreateSerializer(common.AddressDetailSerializer):
    """Address create serializer."""


class CountryBackSerializer(common.CountrySerializer):
    """Country back-office serializer."""

    class Meta:
        model = models.Country
        fields = [
            'id',
            'code',
            'svg_image',
            'name',
            'country_id'
        ]


class CityGallerySerializer(serializers.ModelSerializer):
    """Serializer class for model CityGallery."""

    class Meta:
        """Meta class"""

        model = models.CityGallery
        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."""
        city_pk = self.request_kwargs.get('pk')
        image_id = self.request_kwargs.get('image_id')

        city_qs = models.City.objects.filter(pk=city_pk)
        image_qs = Image.objects.filter(id=image_id)

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

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

        city = city_qs.first()
        image = image_qs.first()

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

        attrs['city'] = city
        attrs['image'] = image

        return attrs
