import enum
from typing import List, TypedDict

from vbv_lernwelt.core.models import User
from vbv_lernwelt.course.services import mark_course_completion
from vbv_lernwelt.course_session.models import CourseSessionAttendanceCourse


class AttendanceUserStatus(enum.Enum):
    PRESENT = "PRESENT"
    ABSENT = "ABSENT"


class AttendanceUser(TypedDict):
    user_id: str
    status: AttendanceUserStatus


def update_attendance_list(
    attendance_course: CourseSessionAttendanceCourse,
    attendance_user_list: List[AttendanceUser],
):
    user_id_set_before = set(
        [u["user_id"] for u in attendance_course.attendance_user_list]
    )

    result_user_list = []
    for attendance_user in attendance_user_list:
        u = User.objects.filter(id=attendance_user.get("user_id")).first()
        if u is not None:
            result_user_list.append(
                {
                    "user_id": str(u.id),
                    "status": attendance_user.get(
                        "status", AttendanceUserStatus.PRESENT
                    ).value,
                    "email": u.email,
                    "first_name": u.first_name,
                    "last_name": u.last_name,
                }
            )
            completion_status = (
                "SUCCESS"
                if attendance_user.get("status").value == "PRESENT"
                else "FAIL"
            )
            mark_course_completion(
                page=attendance_course.learning_content,
                user=u,
                course_session=attendance_course.course_session,
                completion_status=completion_status,
            )

    attendance_course.attendance_user_list = result_user_list
    attendance_course.save()

    user_id_set_after = set(
        [u["user_id"] for u in attendance_course.attendance_user_list]
    )

    user_id_set_removed = user_id_set_before - user_id_set_after

    for user_id in user_id_set_removed:
        u = User.objects.filter(id=user_id).first()
        if u is not None:
            mark_course_completion(
                page=attendance_course.learning_content,
                user=u,
                course_session=attendance_course.course_session,
                completion_status="FAIL",
            )

    return attendance_course
