from django.conf import settings
from django.contrib.auth import get_user_model
from django.template import loader

from intranet.femida.src.comments.controllers import update_or_create_comment
from intranet.femida.src.core.serializers import StartrekUniqueField
from intranet.femida.src.interviews.choices import INTERVIEW_REVIEW_REASONS, AA_TYPES
from intranet.femida.src.notifications.utils import get_base_context
from intranet.femida.src.startrek.operations import IssueUpdateOperation
from intranet.femida.src.startrek.utils import create_issue
from intranet.femida.src.utils.inflector import inflect_fio


User = get_user_model()


def _get_review_issue_summary(interview):
    aa_prefixes = {
        AA_TYPES.lite: 'AA (lite) ',
        AA_TYPES.easy: 'AA (easy) ',
    }
    prefix = ''
    if interview.is_aa:
        prefix = aa_prefixes.get(interview.aa_type, 'AA-')

    return 'Ревью {prefix}секции {candidate}. {action} {interviewer}'.format(
        prefix=prefix,
        candidate=inflect_fio(interview.candidate.get_full_name(), 2),
        action='Провёл' if interview.interviewer.gender == 'male' else 'Провела',
        interviewer=interview.interviewer.get_full_name(),
    )


def _get_aa_review_issue_comment(assignee):
    template_name = 'startrek/interviews/aa-review-invite-reviewer.wiki'
    body = loader.render_to_string(template_name)
    return {
        'text': body,
        'summonees': [assignee] if assignee else None,
    }


def _get_review_reason(interview, initiator):
    if interview.is_aa:
        return None

    if initiator:
        return INTERVIEW_REVIEW_REASONS.request
    elif interview.is_finished_by_newbie:
        return INTERVIEW_REVIEW_REASONS.newbie
    else:
        return INTERVIEW_REVIEW_REASONS.random


def create_review_issue(interview, queue, initiator=None, assignee=None, comment=None):
    template_name = 'startrek/interviews/aa-review-issue.wiki'
    context = get_base_context()
    context['interview'] = interview
    context['initiator'] = initiator
    context['comment'] = comment
    review_reason = _get_review_reason(interview, initiator)

    params = {
        'queue': queue,
        'summary': _get_review_issue_summary(interview),
        'description': loader.render_to_string(template_name, context),
        'followers': [initiator.username] if initiator else [],
        'unique': StartrekUniqueField.generate(interview, queue),
        'interviewer': interview.interviewer.username,
        'assignee': assignee,
    }
    if review_reason:
        params['tags'] = [review_reason]
    # Для всех секций, кроме AA-архитектуры, скрининга и если это не одна из первых секций
    # для собеседующего, добавляем комментарий, призывая исполнителя
    is_review_comment_needed = not (
        interview.is_screening
        or interview.is_finished_by_newbie
        or interview.is_aa_architecture
    )
    if is_review_comment_needed:
        params['comment'] = _get_aa_review_issue_comment(assignee)

    issue = create_issue(**params)
    interview.startrek_review_key = issue.key
    interview.save()

    if comment:
        data = {
            'related_object': interview,
            'text': f'{comment}\n{interview.startrek_review_key}',
        }
        update_or_create_comment(data, initiator)

    return issue


def update_review_issue(interview, initiator, comment):
    template_name = 'startrek/interviews/review-issue-comment.wiki'
    context = get_base_context()
    context['comment'] = comment
    context['initiator'] = initiator

    operation = IssueUpdateOperation(interview.startrek_review_key)
    operation(
        comment=loader.render_to_string(template_name, context),
        followers={
            'add': [initiator.username],
        },
    )


def create_aa_entry_issue(applicant, answers):
    template_name = 'startrek/interviews/aa-entry-issue.wiki'
    context = get_base_context()
    context['applicant'] = applicant
    context['answers'] = answers

    return create_issue(
        queue=settings.STARTREK_AA_QUEUE,
        summary='{full_name} ({username}@)'.format(
            full_name=applicant.get_full_name(),
            username=applicant.username,
        ),
        description=loader.render_to_string(template_name, context),
        followers=[applicant.username],
        unique=StartrekUniqueField.generate(applicant, settings.STARTREK_AA_QUEUE, 'date_joined'),

        # FIXME: Хардкод. Позже сделаем random, как с AAREV
        assignee='elric',
    )
