from typing import List
from django.shortcuts import get_object_or_404
from ninja import ModelSchema, Router
from .models import Rapid, Exam

from .decorators import user_is_author_or_rapid_checker
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

router = Router()


class RapidSchema(ModelSchema):
    # `ninja` newer versions require an inner `Meta` class instead of `Config`
    # for ModelSchema. Replace `Config` with `Meta` to be compatible.
    class Meta:
        model = Rapid
        #model_fields (old API) -> use `fields` per newer ninja ModelSchema API
        #fields can be a list of field names or the string "__all__".
        #fields = ["question", "history", "feedback", "normal", "laterality"]
        fields = "__all__"

class ExamSchema(ModelSchema):
    class Meta:
        model = Exam
        fields = ["id", "name", "active", "publish_results"]

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

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

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


@router.get('/user_exams', response=List[ExamSchema], url_name="rapids_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="rapid_checker").exists():
        return Exam.objects.filter(archive=False).order_by('name')

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