import django_filters

from .models import AnatomyQuestion, UserAnswer, Exam

#from generic.filters import UserAnswerFilter
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="anatomy_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="anatomy_checker").exists():
        queryset = User.objects.filter(id=request.user.id)
    else:
        queryset = User.objects.all()

    return queryset


class AnatomyQuestionFilter(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 = AnatomyQuestion
        fields = ("question_type",
        "examination", 
        "modality", "region",
                  "body_part", "created_date", "open_access")

    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="anatomy_checker").exists():
                queryset = queryset.filter(open_access=True) | queryset.filter(author__id=request.user.id)
        super(AnatomyQuestionFilter, self).__init__(data=data, queryset=queryset, prefix=prefix, request=request)
        pass

class AnatomyUserAnswerFilter(django_filters.FilterSet):
    class Meta:
        model= UserAnswer
        fields = (
            "cid",
            "user",
            #"question",
            "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="anatomy_checker").exists():
                queryset = queryset.filter(exam__open_access=True) | queryset.filter(exam__author__id=request.user.id)
        #queryset = queryset.prefetch_related("question", "question__question_type", "exam")
        super(AnatomyUserAnswerFilter, self).__init__(data=data, queryset=queryset, prefix=prefix, request=request)
        pass