from typing import List

from rest_framework import serializers
from rest_framework.renderers import JSONRenderer

from vbv_lernwelt.core.models import Organisation, User
from vbv_lernwelt.course.models import CourseSessionUser
from vbv_lernwelt.course_session_group.models import CourseSessionGroup


def create_json_from_objects(objects, serializer_class, many=True) -> str:
    serializer = serializer_class(objects, many=many)
    return JSONRenderer().render(serializer.data).decode("utf-8")


class UserSerializer(serializers.ModelSerializer):
    course_session_experts = serializers.SerializerMethodField()

    class Meta:
        model = User
        fields = [
            "id",
            "first_name",
            "last_name",
            "email",
            "username",
            "avatar_url",
            "organisation",
            "is_superuser",
            "course_session_experts",
            "language",
        ]
        read_only_fields = [
            "id",
            "is_superuser",
            "first_name",
            "last_name",
            "email",
            "username",
        ]

    def get_course_session_experts(self, obj: User) -> List[str]:
        supervisor_in_session_ids = set(
            CourseSessionGroup.objects.filter(supervisor=obj).values_list(
                "course_session__id", flat=True
            )
        )

        expert_in_session_ids = set(
            CourseSessionUser.objects.filter(
                role=CourseSessionUser.Role.EXPERT, user=obj
            ).values_list("course_session__id", flat=True)
        )

        return [str(_id) for _id in (supervisor_in_session_ids | expert_in_session_ids)]


class OrganisationSerializer(serializers.ModelSerializer):
    class Meta:
        model = Organisation
        fields = "__all__"
