import graphene
from rest_framework.exceptions import PermissionDenied

from vbv_lernwelt.assignment.graphql.types import (
    AssignmentCompletionType,
    AssignmentType,
)
from vbv_lernwelt.assignment.models import Assignment, AssignmentCompletion
from vbv_lernwelt.course.graphql.types import resolve_course_page
from vbv_lernwelt.course.models import CourseSession
from vbv_lernwelt.course.permissions import has_course_access, is_course_session_expert


class AssignmentQuery(object):
    assignment = graphene.Field(
        AssignmentType, id=graphene.ID(), slug=graphene.String()
    )

    def resolve_assignment(root, info, id=None, slug=None):
        return resolve_course_page(Assignment, root, info, id=id, slug=slug)

    assignment_completion = graphene.Field(
        AssignmentCompletionType,
        assignment_id=graphene.ID(required=True),
        course_session_id=graphene.ID(required=True),
        assignment_user_id=graphene.ID(required=False),
    )

    def resolve_assignment_completion(
        root, info, assignment_id, course_session_id, assignment_user_id=None, **kwargs
    ):
        if assignment_user_id is None:
            assignment_user_id = info.context.user.id

        if str(assignment_user_id) == str(
            info.context.user.id
        ) or is_course_session_expert(info.context.user, course_session_id):
            course_id = CourseSession.objects.get(id=course_session_id).course_id
            if has_course_access(info.context.user, course_id):
                return AssignmentCompletion.objects.filter(
                    assignment_user_id=assignment_user_id,
                    assignment_id=assignment_id,
                    course_session_id=course_session_id,
                ).first()
        raise PermissionDenied()
