from rest_framework import serializers

from intranet.femida.src.api.core.serializers import (
    FemidaSerializer,
    AwareSerializerMixin,
    IdSlugNameSerializer,
)
from intranet.femida.src.core.models import City, Country


class CountryLiteSerializer(serializers.ModelSerializer):

    name = serializers.ReadOnlyField()

    class Meta:
        model = Country
        fields = ('id', 'name', 'code')


class CitySerializer(AwareSerializerMixin, FemidaSerializer):

    name = serializers.ReadOnlyField()
    country = CountryLiteSerializer()
    services = serializers.SerializerMethodField()
    publications_count = serializers.SerializerMethodField()

    def get_services(self, obj):
        if 'public_service_by_id' not in self.root.context:
            return []

        public_service_by_id = self.root.context['public_service_by_id']
        service_ids_by_city_id = self.root.context['service_ids_by_city_id']

        service_ids = service_ids_by_city_id.get(obj.id, ())
        services = [
            public_service_by_id[service_id]
            for service_id in service_ids
            if service_id in public_service_by_id
        ]
        services_data = IdSlugNameSerializer(services, many=True).data
        for service in services_data:
            service['priority'] = self.get_service_priority(obj.id, service['id'])

        return services_data

    def get_service_priority(self, city_id, service_id) -> int:
        publication_counts = self.root.context.get('service_publications_count_by_city', {})
        return publication_counts.get((city_id, service_id), 0)

    def get_publications_count(self, obj):
        if 'publications_count_by_city_id' not in self.root.context:
            return None
        publications_count_data = self.root.context['publications_count_by_city_id']
        return publications_count_data.get(obj.id, 0)

    class Meta:
        model = City
        fields = (
            'id',
            'name',
            'slug',
            'country',
            'services',
            'publications_count',
        )

        select_related_map = {
            'country': ('country',),
        }
