from django.conf import settings
from django.template import loader

from intranet.femida.src.candidates.submissions.helpers import (
    get_applications_waiting_contest_results,
)
from intranet.femida.src.notifications.utils import get_base_context, get_communication_message_id
from intranet.femida.src.tasks import send_email


def _notify_candidate_about_contest(submission, template_name, on_transaction_commit=True):
    email = submission.email
    context = get_base_context()
    context['submission'] = submission
    body = loader.render_to_string(template_name, context)

    application = get_applications_waiting_contest_results([submission.id]).first()
    if application is not None:
        message_id = get_communication_message_id(application.candidate)
    else:
        message_id = None

    send_email.apply_async(
        kwargs={
            'subject': 'От компании Яндекс',
            'body': body,
            'to': [email],
            'from_email': settings.JOB_EMAIL_VERBOSE,
            'message_id': message_id,
            'is_external': True,
        },
        on_transaction_commit=on_transaction_commit,
    )


def notify_about_failed_registration_to_contest(submission):
    _notify_candidate_about_contest(
        submission=submission,
        template_name='email/contest/re-register.html',
        on_transaction_commit=False,
    )


def notify_about_successful_registration_to_contest(submission):
    _notify_candidate_about_contest(
        submission=submission,
        template_name='email/contest/register.html',
        on_transaction_commit=True,
    )
