import graphene
import structlog
from rest_framework.exceptions import PermissionDenied

from vbv_lernwelt.course_session.graphql.types import (
    CourseSessionAttendanceCourseObjectType,
)
from vbv_lernwelt.course_session.models import CourseSessionAttendanceCourse
from vbv_lernwelt.course_session.services.attendance import (
    AttendanceUserStatus,
    update_attendance_list,
)
from vbv_lernwelt.iam.permissions import has_course_access

logger = structlog.get_logger(__name__)


class AttendanceUserInputType(graphene.InputObjectType):
    user_id = graphene.UUID(required=True)
    status = graphene.Field(
        graphene.Enum.from_enum(AttendanceUserStatus), required=True
    )


class AttendanceCourseUserMutation(graphene.Mutation):
    course_session_attendance_course = graphene.Field(
        CourseSessionAttendanceCourseObjectType
    )

    class Input:
        id = graphene.ID(required=True)
        attendance_user_list = graphene.List(AttendanceUserInputType, required=True)

    @classmethod
    def mutate(
        cls,
        root,
        info,
        id,
        attendance_user_list,
    ):
        attendance_course = CourseSessionAttendanceCourse.objects.get(id=id)

        if not attendance_course or not has_course_access(
            info.context.user,
            attendance_course.course_session.course_id,
        ):
            raise PermissionDenied()

        attendance_course = update_attendance_list(
            attendance_course=attendance_course,
            attendance_user_list=attendance_user_list,
        )

        return AttendanceCourseUserMutation(
            course_session_attendance_course=attendance_course
        )


class CourseSessionMutation:
    update_course_session_attendance_course_users = AttendanceCourseUserMutation.Field()
