"""File containing Members application views."""

from django.conf import settings
from django.utils.translation import ugettext as _

# Email validation
from django.db.models.signals import post_save
from django.dispatch import receiver

import logging
from smtplib import SMTPAuthenticationError

from members.models import Member, Request
from members.views.utils import send_mail_wrapper


@receiver(post_save, sender=Request)
def email_on_request(sender, instance, created, **kwargs):
    """Send email validation."""
    if not settings.ENABLE_AUTOMATIC_EMAILS:
        return

    try:
        if created:
            subject = 'Test1'
            message = 'Please validate your email address\r\n'
            send_mail_wrapper(subject, message, instance.email)
    except SMTPAuthenticationError:
        logging.error('Failed to send email to accepted request!')


@receiver(post_save, sender=Member)
def email_on_accept(sender, instance, created, **kwargs):
    """Send email to accepted member."""
    if not settings.ENABLE_AUTOMATIC_EMAILS:
        return

    try:
        if created:
            subject = 'Test2'
            message = 'Jäsenhakemuksesi on hyväksytty!!!\r\n'
            send_mail_wrapper(subject, message, instance.email)
    except SMTPAuthenticationError:
        logging.error('Failed to send email to accepted member!')
