from rest_framework import serializers
from django_countries.serializers import CountryFieldMixin

from ichec_django_core.models import Organization, Address


class AddressSerializer(CountryFieldMixin, serializers.HyperlinkedModelSerializer):
    class Meta:
        model = Address
        fields = [
            "line1",
            "line2",
            "line3",
            "city",
            "region",
            "postcode",
            "country",
            "country_name",
            "country_flag",
            "id",
            "url",
        ]
        read_only_fields = ["country_name", "country_flag", "id", "url"]


class OrganizationBaseSerializer(serializers.HyperlinkedModelSerializer):
    class Meta:
        model = Organization
        fields = [
            "name",
            "acronym",
            "description",
            "address",
            "website",
            "id",
            "url",
            "created_at",
            "updated_at",
        ]
        read_only_fields = ["url", "id", "created_at", "updated_at"]


class OrganizationListSerializer(OrganizationBaseSerializer):
    pass


class OrganizationDetailSerializer(OrganizationBaseSerializer):
    address = AddressSerializer()

    def create(self, validated_data):
        address_data = validated_data.pop("address")
        address = Address.objects.create(**address_data)
        return Organization.objects.create(address=address, **validated_data)

    def update(self, instance, validated_data):
        address_data = validated_data.pop("address")

        instance = super().update(instance, validated_data)
        for attr, value in address_data.items():
            setattr(instance.address, attr, value)
        return instance
