from typing import List
from django.shortcuts import get_object_or_404
from ninja import ModelSchema, Router
from .models import Question, 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 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_question_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="sbas_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="sbas_checker").exists():
        return Exam.objects.filter(archive=False).order_by('name')

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