from typing import List

from rest_framework import serializers

from vbv_lernwelt.competence.models import PerformanceCriteria
from vbv_lernwelt.core.serializers import UserSerializer
from vbv_lernwelt.course.models import CourseCompletion, CourseCompletionStatus
from vbv_lernwelt.self_evaluation_feedback.models import (
    CourseCompletionFeedback,
    SelfEvaluationFeedback,
)


class SelfEvaluationFeedbackSerializer(serializers.ModelSerializer):
    criteria = serializers.SerializerMethodField()
    feedback_requester_user = UserSerializer(read_only=True)
    feedback_provider_user = UserSerializer(read_only=True)
    learning_unit_id = serializers.PrimaryKeyRelatedField(
        read_only=True, source="learning_unit"
    )
    feedback_id = serializers.PrimaryKeyRelatedField(read_only=True, source="id")
    circle_name = serializers.SerializerMethodField()
    title = serializers.CharField(source="learning_unit.title")

    class Meta:
        model = SelfEvaluationFeedback
        fields = [
            "feedback_id",
            "title",
            "circle_name",
            "learning_unit_id",
            "feedback_submitted",
            "feedback_requester_user",
            "feedback_provider_user",
            "criteria",
        ]

    def get_circle_name(self, obj):
        return obj.learning_unit.get_circle().title

    def get_criteria(self, obj):
        performance_criteria: List[
            PerformanceCriteria
        ] = obj.learning_unit.performancecriteria_set.all()

        criteria = []

        for pc in performance_criteria:
            # requester self assessment
            completion = CourseCompletion.objects.filter(
                page_id=pc.id,
                user=obj.feedback_requester_user,
            ).first()

            self_assessment = (
                completion.completion_status
                if completion
                else CourseCompletionStatus.UNKNOWN.value
            )

            # provider feedback assessment
            feedback = CourseCompletionFeedback.objects.filter(
                course_completion=completion
            ).first()

            feedback_assessment = (
                feedback.feedback_assessment
                if feedback
                else CourseCompletionStatus.UNKNOWN.value
            )

            criteria.append(
                {
                    "course_completion_id": completion.id if completion else None,
                    "title": pc.title,
                    "self_assessment": self_assessment,
                    "feedback_assessment": feedback_assessment,
                }
            )

        return criteria
