from django.contrib.auth.models import Group, Permission
from rest_framework import serializers

from ichec_django_core.models import Member

SERIALIZER_BASE_FIELDS = ("id", "url", "created_at", "updated_at")


class MemberBaseSerializer(serializers.HyperlinkedModelSerializer):

    class Meta:
        model = Member
        fields = SERIALIZER_BASE_FIELDS + (
            "username",
            "email",
            "first_name",
            "last_name",
            "phone",
            "organizations",
            "is_facility_member",
            "profile",
            "profile_thumbnail",
            "all_permissions",
        )
        read_only_fields = SERIALIZER_BASE_FIELDS + (
            "is_facility_member",
            "all_permissions",
            "profile_thumbnail",
        )


class MemberResponseSerializer(MemberBaseSerializer):

    profile = serializers.HyperlinkedIdentityField(
        read_only=True, view_name="member_profiles"
    )
    profile_thumbnail = serializers.HyperlinkedIdentityField(
        read_only=True, view_name="member_profile_thumbnails"
    )

    class Meta:
        model = Member
        fields = MemberBaseSerializer.Meta.fields
        read_only_fields = MemberBaseSerializer.Meta.read_only_fields + ("profile",)

    def to_representation(self, instance):
        rep = super().to_representation(instance)
        if not instance.profile:
            rep["profile"] = None
        if not instance.profile_thumbnail:
            rep["profile_thumbnail"] = None
        return rep


class MemberSerializer(MemberBaseSerializer):
    class Meta:
        model = Member
        fields = MemberBaseSerializer.Meta.fields
        read_only_fields = MemberBaseSerializer.Meta.read_only_fields

    def to_representation(self, instance):
        return MemberResponseSerializer(context=self.context).to_representation(
            instance
        )


class GroupSerializer(serializers.HyperlinkedModelSerializer):
    class Meta:
        model = Group
        fields = ["url", "name", "id"]


class PermissionSerializer(serializers.HyperlinkedModelSerializer):
    class Meta:
        model = Permission
        fields = ["url", "id", "codename"]
