from django.db.models import Avg

from intranet.femida.src.candidates.filters.fields.base import register_filter, FieldFilter
from intranet.femida.src.candidates.filters.fields.base.equal import Equal
from intranet.femida.src.candidates.filters.fields.interviews.conditions import (
    WithoutNoHire,
    AllNoHire,
    GradeRange,
)
from intranet.femida.src.candidates.filters.fields.interviews.forms import (
    AAInterviewNoHireForm,
    AAInterviewGradeRangeForm,
    InterviewGradeFilterForm,
)
from intranet.femida.src.interviews.choices import INTERVIEW_STATES
from intranet.femida.src.interviews.models import Interview


@register_filter
class InterviewGradeFilter(FieldFilter):

    condition_classes = [Equal]
    form_base = InterviewGradeFilterForm

    @classmethod
    def get_queryset(cls):
        return (
            Interview.unsafe
            .gradable()
            .filter(state=INTERVIEW_STATES.finished)
            .values('candidate_id')
            .annotate(avg_grade=Avg('grade'))
        )


@register_filter
class AAInterviewFilter(FieldFilter):

    condition_classes = [
        WithoutNoHire,
        AllNoHire,
        GradeRange.get_cls_with_form(AAInterviewGradeRangeForm),
    ]
    form_base = AAInterviewNoHireForm

    @classmethod
    def get_queryset(cls):
        return Interview.unsafe.aa().filter(state=INTERVIEW_STATES.finished)
