import graphene
from django.core.exceptions import ObjectDoesNotExist, PermissionDenied
from graphene import relay
from graphene_django import DjangoObjectType

from assignments.models import Assignment, StudentSubmission, SubmissionFeedback
from books.utils import are_solutions_enabled_for


class SubmissionFeedbackNode(DjangoObjectType):
    class Meta:
        model = SubmissionFeedback
        filter_fields = []
        interfaces = (relay.Node,)


class StudentSubmissionNode(DjangoObjectType):
    submission_feedback = graphene.Field(SubmissionFeedbackNode)

    class Meta:
        model = StudentSubmission
        filter_fields = []
        interfaces = (relay.Node,)

    def resolve_submission_feedback(self, info, **kwargs):

        user = info.context.user

        if not hasattr(self, 'submission_feedback'):
            return None

        # teacher path
        if user.has_perm('users.can_manage_school_class_content'):
            if self.submission_feedback.teacher == user:
                return self.submission_feedback
            else:
                raise PermissionDenied('Missing permissions')

        # student path

        if self.submission_feedback.final:
            return self.submission_feedback

        return None


class AssignmentNode(DjangoObjectType):
    submission = graphene.Field(StudentSubmissionNode)
    submissions = graphene.List(StudentSubmissionNode)

    class Meta:
        model = Assignment
        filter_fields = []
        interfaces = (relay.Node,)

    def resolve_submission(self, info, **kwargs):
        return self.submissions.filter(student=info.context.user).first()  #  returns None if it doesn't exist yet

    def resolve_submissions(self, info, **kwargs):
        user = info.context.user
        if user.has_perm('users.can_manage_school_class_content'):
            return self.submissions.filter(student__in=user.users_in_same_school_class()).filter(final=True)
        return []

    def resolve_solution(self, info, **kwargs):
        if (info.context.user.is_teacher() or are_solutions_enabled_for(info.context.user, self.module)) and self.solution is not None:
            return self.solution
        else:
            return None
