import graphene
from django.db.models import Q
from graphql import GraphQLError

from vbv_lernwelt.course.graphql.types import CourseObjectType, CourseSessionObjectType
from vbv_lernwelt.course.models import Course, CourseSession
from vbv_lernwelt.iam.permissions import has_course_access
from vbv_lernwelt.learnpath.graphql.types import (
    LearningContentAssignmentObjectType,
    LearningContentAttendanceCourseObjectType,
    LearningContentDocumentListObjectType,
    LearningContentEdoniqTestObjectType,
    LearningContentFeedbackUKObjectType,
    LearningContentFeedbackVVObjectType,
    LearningContentKnowledgeAssessmentObjectType,
    LearningContentLearningModuleObjectType,
    LearningContentMediaLibraryObjectType,
    LearningContentPlaceholderObjectType,
    LearningContentRichTextObjectType,
    LearningContentVideoObjectType,
)


class CourseQuery(graphene.ObjectType):
    course = graphene.Field(
        CourseObjectType,
        id=graphene.ID(),
        slug=graphene.String(),
    )
    course_session = graphene.Field(CourseSessionObjectType, id=graphene.ID())

    def resolve_course(self, info, id=None, slug=None):
        if id is None and slug is None:
            raise GraphQLError("Either 'id', 'slug' must be provided.")
        course = Course.objects.get(Q(id=id) | Q(slug=slug))
        if has_course_access(info.context.user, course):
            return course
        raise PermissionError("You do not have access to this course")

    def resolve_course_session(self, info, id):
        course_session = CourseSession.objects.get(pk=id)
        if has_course_access(info.context.user, course_session.course):
            return course_session
        raise PermissionError("You do not have access to this course session")

    # dummy import, so that graphene recognizes the types
    learning_content_media_library = graphene.Field(
        LearningContentMediaLibraryObjectType
    )
    learning_content_assignment = graphene.Field(LearningContentAssignmentObjectType)
    learning_content_attendance_course = graphene.Field(
        LearningContentAttendanceCourseObjectType
    )
    learning_content_feedback_uk = graphene.Field(LearningContentFeedbackUKObjectType)
    learning_content_feedback_vv = graphene.Field(LearningContentFeedbackVVObjectType)
    learning_content_learning_module = graphene.Field(
        LearningContentLearningModuleObjectType
    )
    learning_content_knowledge_assessment = graphene.Field(
        LearningContentKnowledgeAssessmentObjectType
    )
    learning_content_placeholder = graphene.Field(LearningContentPlaceholderObjectType)
    learning_content_rich_text = graphene.Field(LearningContentRichTextObjectType)
    learning_content_test = graphene.Field(LearningContentEdoniqTestObjectType)
    learning_content_video = graphene.Field(LearningContentVideoObjectType)
    learning_content_document_list = graphene.Field(
        LearningContentDocumentListObjectType
    )
