from rest_framework import serializers
from rest_framework.renderers import JSONRenderer

from vbv_lernwelt.core.models import User
from vbv_lernwelt.course.models import CourseSessionUser


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",
            "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):
        qs = CourseSessionUser.objects.filter(
            role=CourseSessionUser.Role.EXPERT, user=obj
        )

        return [csu.course_session.id for csu in qs]
