import django_filters

from .models import Question, UserAnswer, Exam
from django.contrib.auth.models import User


def get_exams(request):
    if request is None:
        return Exam.objects.none()

    if not request.user.groups.filter(name="shorts_checker").exists():
        queryset = Exam.objects.filter(author__id=request.user.id)
    else:
        queryset = Exam.objects.all()

    return queryset


def get_authors(request):
    if request is None:
        return User.objects.none()

    if not request.user.groups.filter(name="shorts_checker").exists():
        queryset = User.objects.filter(id=request.user.id)
    else:
        queryset = User.objects.all()

    return queryset


class QuestionFilter(django_filters.FilterSet):
    exams = django_filters.ModelMultipleChoiceFilter(
        queryset=get_exams, null_label="No exam"
    )
    author = django_filters.ModelMultipleChoiceFilter(
        queryset=get_authors, null_label="No author"
    )

    class Meta:
        model = Question
        fields = { 
            "examination": ["exact"],
            # "site",
            "created_date": ["exact"],
            "open_access": ["exact"],
         }

    def __init__(
        self,
        data=None,
        queryset=None,
        prefix=None,
        strict=None,
        user=None,
        request=None,
    ):
        if not request.user.groups.filter(name="shorts_checker").exists():
            queryset = queryset.filter(open_access=True) | queryset.filter(
                author__id=request.user.id
            )
        super(QuestionFilter, self).__init__(
            data=data, queryset=queryset, prefix=prefix, request=request
        )
        pass


class QuestionUserAnswerFilter(django_filters.FilterSet):
    class Meta:
        model = UserAnswer
        fields = (
            "cid",
            "user",
            "answer",
            # "answer_compare",
            "exam",
            "created",
            "updated",
        )

    def __init__(
        self,
        data=None,
        queryset=None,
        prefix=None,
        strict=None,
        user=None,
        request=None,
    ):
        if not request.user.is_superuser:
            if not request.user.groups.filter(name="shorts_checker").exists():
                queryset = queryset.filter(exam__open_access=True) | queryset.filter(
                    exam__author__id=request.user.id
                )
        super(QuestionUserAnswerFilter, self).__init__(
            data=data, queryset=queryset, prefix=prefix, request=request
        )
        pass
