from django.conf import settings
from django.core.mail import send_mail
from django.db.models.signals import post_save
from django.dispatch import receiver
from django.template.loader import render_to_string

from .models import JobApplication


@receiver(post_save, sender=JobApplication)
def on_application_created(sender, instance, created, **kwargs):
    if not created:
        return

    # Email to applicant
    subject_applicant = render_to_string(
        'careers/emails/application_received_subject.txt',
        {'application': instance}
    ).strip()
    body_applicant = render_to_string(
        'careers/emails/application_received_body.txt',
        {'application': instance}
    )
    send_mail(
        subject=subject_applicant,
        message=body_applicant,
        from_email=settings.DEFAULT_FROM_EMAIL,
        recipient_list=[instance.email],
        fail_silently=True,
    )

    # Email to HR
    subject_hr = render_to_string(
        'careers/emails/new_application_admin_subject.txt',
        {'application': instance}
    ).strip()
    body_hr = render_to_string(
        'careers/emails/new_application_admin_body.txt',
        {'application': instance}
    )
    send_mail(
        subject=subject_hr,
        message=body_hr,
        from_email=settings.DEFAULT_FROM_EMAIL,
        recipient_list=[settings.CAREERS_NOTIFY_EMAIL],
        fail_silently=True,
    )
