from intranet.femida.src.candidates.consideration_issues.issue_types import (
    ExtendedStatusChangedIssueType,
    InterviewNotFinishedIssueType,
    CandidateModifiedIssueType,
)
from intranet.femida.src.candidates.signals import (
    candidate_modified,
    consideration_status_changed,
)
from intranet.femida.src.candidates.tasks import resolve_consideration_issue_task
from intranet.femida.src.interviews.signals import interview_cancelled, interview_finished
from intranet.femida.src.permissions.context import context, EmptyContextException


def resolve(issue_type, **params) -> dict:

    issue_type_name = issue_type.type_name

    def inner(initiator=None, **kwargs):
        if initiator is None:
            try:
                initiator = context.user
            except EmptyContextException:
                pass
        if initiator and initiator.is_anonymous:
            initiator = None

        consideration = kwargs.get('consideration')
        candidate = kwargs.get('candidate')
        interview = kwargs.get('interview')
        if not consideration:
            if candidate:
                consideration = candidate.last_consideration
            elif interview:
                consideration = interview.consideration
        if not consideration:
            return

        resolve_consideration_issue_task.delay(
            issue_type_name,
            consideration.id,
            initiator.id if initiator else None,
        )

    return {
        'receiver': inner,
        'dispatch_uid': f'resolve_issue_{issue_type_name}',
        'weak': False,
    }


candidate_modified.connect(**resolve(CandidateModifiedIssueType))
consideration_status_changed.connect(**resolve(ExtendedStatusChangedIssueType))
interview_cancelled.connect(**resolve(InterviewNotFinishedIssueType))
interview_finished.connect(**resolve(InterviewNotFinishedIssueType))
