from django_filters import rest_framework as filters
from django.utils import timezone
from apps.system.models import User
from .models import Exam, ExamRecord

class ExamFilter(filters.FilterSet):
    can_attend = filters.BooleanFilter(method='filter_can_attend')
    is_my = filters.BooleanFilter(method='filter_is_my')
    class Meta:
        model = Exam
        fields = {
            'close_time': ['gte', 'lte'],
            'paper': ['exact'],
            'is_public': ['exact'],
        }

    def filter_can_attend(self, queryset, name, value):
        if value:
            now = timezone.now()
            return queryset.filter(open_time__lte=now, close_time__gte=now)| queryset.filter(close_time__isnull=True)
        return queryset
    
    def filter_is_my(self, queryset, name, value):
        if value:
            user:User = self.request.user
            dept = user.belong_dept
            qs = queryset.filter(is_public=True)
            qs = qs|qs.filter(p_users=user)
            if dept:
                qs = qs|qs.filter(p_depts=dept)
            return qs
        return queryset
    
class ExamRecordFilter(filters.FilterSet):
    is_my = filters.BooleanFilter(method='filter_is_my')
    class Meta:
        model = ExamRecord
        fields = {
            'start_time': ['exact', 'gte', 'lte'],
            'is_pass': ['exact'],
            'is_submited': ['exact'],
            'exam': ['exact'],
        }
    def filter_is_my(self, queryset, name, value):
        if value:
            user = self.request.user
            return queryset.filter(create_by=user)
        return queryset