from rest_framework.fields import SerializerMethodField

from vbv_lernwelt.competence.serializers import (
    PerformanceCriteriaLearningPathSerializer,
)
from vbv_lernwelt.core.utils import get_django_content_type
from vbv_lernwelt.course.serializer_helpers import get_course_serializer_class
from vbv_lernwelt.learnpath.models import (
    LearningContentAssignment,
    LearningContentEdoniqTest,
    LearningUnit,
)


class LearningUnitSerializer(
    get_course_serializer_class(
        LearningUnit,
        field_names=[
            "evaluate_url",
            "course_category",
            "children",
            "title_hidden",
            "feedback_user",
        ],
    )
):
    evaluate_url = SerializerMethodField()

    def get_children(self, obj):
        return [
            PerformanceCriteriaLearningPathSerializer(child).data
            for child in obj.performancecriteria_set.all()
        ]

    def get_evaluate_url(self, obj):
        return obj.get_evaluate_url()


class LearningUnitPerformanceCriteriaSerializer(
    get_course_serializer_class(
        LearningUnit,
        field_names=[
            "evaluate_url",
            "course_category",
        ],
    )
):
    evaluate_url = SerializerMethodField()

    def get_evaluate_url(self, obj):
        return obj.get_evaluate_url()


class LearningContentEdoniqTestSerializer(
    get_course_serializer_class(
        LearningContentEdoniqTest,
        field_names=LearningContentEdoniqTest.serialize_field_names
        + ["competence_certificate"],
    )
):
    # TODO: quickfix before GraphQL learning path
    competence_certificate = SerializerMethodField()

    def get_competence_certificate(self, obj):
        try:
            cert = obj.content_assignment.competence_certificate
            return {
                "id": str(cert.id),
                "title": cert.title,
                "slug": cert.slug,
                "content_type": get_django_content_type(cert),
                "translation_key": cert.translation_key,
                "frontend_url": cert.get_frontend_url(),
            }
        except Exception:
            return None


class LearningContentAssignmentSerializer(
    get_course_serializer_class(
        LearningContentAssignment,
        field_names=LearningContentAssignment.serialize_field_names
        + ["competence_certificate"],
    )
):
    # TODO: quickfix before GraphQL learning path
    competence_certificate = SerializerMethodField()

    def get_competence_certificate(self, obj):
        try:
            cert = obj.content_assignment.competence_certificate
            return {
                "id": str(cert.id),
                "title": cert.title,
                "slug": cert.slug,
                "content_type": get_django_content_type(cert),
                "translation_key": cert.translation_key,
                "frontend_url": cert.get_frontend_url(),
            }
        except Exception:
            return None
