import json

from constance import config
from django.db.models import Case, When, Max, Min, F, DateTimeField
from django.utils.decorators import classproperty

from intranet.femida.src.candidates.consideration_issues.base import (
    register_issue_type,
    DateThresholdIssueType,
)
from intranet.femida.src.interviews.choices import INTERVIEW_STATES


@register_issue_type
class ExtendedStatusChangedIssueType(DateThresholdIssueType):

    type_name = 'extended_status_changed'
    field_name = 'extended_status_changed_at'

    @classproperty
    def thresholds(self):
        return json.loads(config.EXTENDED_STATUS_SLA)

    @classmethod
    def get_annotations(cls):
        # Здесь нельзя делать такие подзапросы как get_extended_status_changed_at_subquery
        # т.к. extended_status_changed_at будет заново вычисляться внутри каждого When()
        # и каждый раз мы будем делать подзапрос к ConsiderationHistory
        # А с таким запросом мы сделаем один LEFT OUTER JOIN
        return {
            'extended_status_changed_at': Max(
                'consideration_history__changed_at',
                output_field=DateTimeField(),
            ),
        }


@register_issue_type
class InterviewNotFinishedIssueType(DateThresholdIssueType):

    type_name = 'interview_not_finished'
    field_name = 'interview_event_at'

    @classproperty
    def thresholds(self):
        return json.loads(config.INTERVIEW_FINISH_SLA)

    @classmethod
    def get_annotations(cls):
        return {
            'interview_event_at': Min(Case(
                When(
                    interviews__state__in=[INTERVIEW_STATES.assigned, INTERVIEW_STATES.estimated],
                    then=F('interviews__event_start_time'),
                ),
                output_field=DateTimeField(),
            )),
        }


@register_issue_type
class CandidateModifiedIssueType(DateThresholdIssueType):

    type_name = 'candidate_modified'
    field_name = 'candidate_modified'

    @classproperty
    def thresholds(self):
        return json.loads(config.CANDIDATE_MODIFIED_SLA)

    @classmethod
    def get_annotations(cls):
        return {'candidate_modified': F('candidate__modified')}
