from http import HTTPStatus
from typing import List
from django.shortcuts import get_object_or_404
from ninja import ModelSchema, Router

from generic.models import CidUser, CidUserExam, ExamUserStatus
from .models import AnatomyQuestion as Question, Exam

from django.core.exceptions import PermissionDenied

from generic.decorators import check_user_in_group
from generic.constants import Group

from ninja.security import django_auth
from ninja.errors import HttpError
from django.conf import settings
from django.contrib.auth import get_user_model

router = Router()

class CidUserSchema(ModelSchema):
    class Meta:
        model = CidUser

        fields = ["cid", "name", "email"]

class UserUserSchema(ModelSchema):
    class Meta:
        model = get_user_model()
        fields = ["id", "email"]

class CidUserExamSchema(ModelSchema):
    cid_user : CidUserSchema | None
    user_user : UserUserSchema | None
    class Meta:
        model = CidUserExam
        fields = ["id"]

class ExamStatusSchema(ModelSchema):
    class Meta:
        model = ExamUserStatus
        fields = ["id", "datetime", "status", "extra"]

class ExamUserStatusSchema(ModelSchema):

    #cid_user : CidUserSchema | None
    #user_user : UserUserSchema | None
    cid_user_exam : CidUserExamSchema | None
    class Meta:
        model = ExamUserStatus
        fields = ["id", "datetime", "status", "extra"]

class QuestionSchema(ModelSchema):
    class Meta:
        model = Question

        fields = "__all__"

        #exclude = ["answers"]

class ExamSchema(ModelSchema):
    class Meta:
        model = Exam

        fields = ["id", "name", "active", "publish_results"]

@router.get('/')
def list_questions(request):
    return [
        {"id": e.id, "normal": e.normal}
        for e in Question.objects.all()
    ]

@router.get('/question/{question_id}', response=QuestionSchema)
@check_user_in_group(Group.cid_user_manager)
def get_rapid_details(request, question_id: int):

    rapid = get_object_or_404(Question, id=question_id)
    return rapid


@router.get('/user_exams', response=List[ExamSchema], url_name="anatomy_user_exams")
def user_exams(request):
    """Returns a list of exams that the user has access to"""
    user = request.user
    if user.groups.filter(name="anatomy_checker").exists():
        return Exam.objects.filter(archive=False).order_by('name')

    return Exam.objects.filter(author__id=user.id, archive=False).order_by('name')


@router.get('/exam/{exam_id}/user_status', response=List[ExamUserStatusSchema])
def get_exam_user_status_all(request, exam_id: int, latest:bool=True):
    exam = get_object_or_404(Exam, id=exam_id)
    if not exam.check_user_can_edit(request.user):
        raise HttpError(HTTPStatus.UNAUTHORIZED,"Exam author required")

    results = exam.exam_user_status.all()
    if latest:
        cid_users = exam.exam_user_status.filter(cid_user_exam__cid_user__isnull=False).order_by("cid_user_exam", "-datetime")#.distinct("cid_user")
        user_users = exam.exam_user_status.filter(cid_user_exam__user_user__isnull=False).order_by("cid_user_exam", "-datetime")#.distinct("user_user")

        results = list(cid_users)
        results.extend(list(user_users))

    return results 

    
@router.get('/exam/{exam_id}/user_status/{cid}/cid', response=List[ExamStatusSchema])
def get_exam_user_status_cid_user(request, exam_id: int, cid: int):
    exam = get_object_or_404(Exam, id=exam_id)
    if not exam.check_user_can_edit(request.user):
        raise HttpError(HTTPStatus.UNAUTHORIZED,"Exam author required")

    return exam.exam_user_status.filter(cid_user_exam__cid_user__cid=cid)

@router.get('/exam/{exam_id}/user_status/{user_id}/user', response=List[ExamStatusSchema])
def get_exam_user_status_user_user(request, exam_id: int, user_id: int):
    exam = get_object_or_404(Exam, id=exam_id)
    if not exam.check_user_can_edit(request.user):
        raise HttpError(HTTPStatus.UNAUTHORIZED,"Exam author required")

    return exam.exam_user_status.filter(cid_user_exam__user_user=user_id)