import django_filters

from .models import Long, LongSeries, Exam, UserAnswer
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="long_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="long_checker").exists():
        queryset = User.objects.filter(id=request.user.id)
    else:
        queryset = User.objects.all()

    return queryset


class LongFilter(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 = Long
        fields = (#"site", 
        "created_date", "open_access", "author")

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

class LongSeriesFilter(django_filters.FilterSet):
    class Meta:
        model = LongSeries
        fields = ("modality","long", "examination", "author")

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

class UserAnswerFilter(django_filters.FilterSet):
    class Meta:
        model = UserAnswer
        fields = (
            "cid",
            #"normal",
            #"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.groups.filter(name="long_checker").exists():
            queryset = queryset.filter(open_access=True) | queryset.filter(author__id=request.user.id)
        super(UserAnswerFilter, self).__init__(data=data, queryset=queryset, prefix=prefix, request=request)
        pass