import graphene
from rest_framework.exceptions import PermissionDenied

from vbv_lernwelt.course.models import CourseSession
from vbv_lernwelt.course_session.graphql.types import (
    CourseSessionAttendanceCourseObjectType,
)
from vbv_lernwelt.course_session.models import CourseSessionAttendanceCourse
from vbv_lernwelt.iam.permissions import has_course_access, is_course_session_expert


class CourseSessionQuery(object):
    course_session_attendance_course = graphene.Field(
        CourseSessionAttendanceCourseObjectType,
        id=graphene.ID(required=True),
        assignment_user_id=graphene.ID(required=False),
    )

    def resolve_course_session_attendance_course(
        root,
        info,
        id=None,
        user_id=graphene.ID(required=False),
    ):
        if user_id is None:
            user_id = info.context.user.id

        attendance_course = CourseSessionAttendanceCourse.objects.filter(
            id=id,
        ).first()

        if attendance_course is None:
            return None

        if str(user_id) == str(info.context.user.id) or is_course_session_expert(
            info.context.user, attendance_course.course_session_id
        ):
            course_id = CourseSession.objects.get(
                id=attendance_course.course_session_id
            ).course_id
            if has_course_access(info.context.user, course_id):
                return attendance_course
        raise PermissionDenied()
