import logging

from django.core.mail import send_mail
from django.template.loader import render_to_string
from django.utils.html import strip_tags
from django.utils.translation import ugettext as _
from django_mailgun import MailgunAPIError
from popojutrze.settings import EMAIL_FROM

logger = logging.getLogger('mailing')


class EmailSender:
    #  Mail testowy
    TEST_SUBJECT = _('E-mail testowy')
    TEST_TEMPLATE = 'mailing/test.html'
    # Rejestracja
    REGISTER_SUBJECT = _('Praesenti - Rejetracja')
    REGISTER_TEMPLATE = 'mailing/register.html'
    # Przypomnienie hasła
    RECOVERY_SUBJECT = _('Praesenti - Zmiana hasła')
    RECOVERY_TEMPLATE = 'mailing/password_recovery.html'
    # Ocena mentora
    MENTOR_SCORE_SUBJECT = _('Praesenti - Ocena mentora')
    MENTOR_SCORE_TEMPLATE = 'mailing/mentor_score.html'

    @staticmethod
    def send_mail(mail_to, subject, html, mail_from=EMAIL_FROM):
        try:
            result = send_mail(subject, strip_tags(html), mail_from, [mail_to], html_message=html, fail_silently=False)
            if not result:
                logger.warning('Cannot send [%s] email to: %s.', subject, mail_to)
            else:
                logger.info('[%s] email sent to: %s', subject, mail_to)
            return result
        except MailgunAPIError as error:
            logger.warning('Cannot send [%s] email to: %s. Error: %s ', subject, mail_to, error)
            return None

    @staticmethod
    def send_test_mail(mail_to, context):
        html = render_to_string(EmailSender.TEST_TEMPLATE, context=context)
        result = EmailSender.send_mail(mail_to, EmailSender.TEST_SUBJECT, html)
        return result

    @staticmethod
    def send_registration_mail(mail_to, context):
        html = render_to_string(EmailSender.REGISTER_TEMPLATE, context=context)
        result = EmailSender.send_mail(mail_to, EmailSender.REGISTER_SUBJECT, html)
        return result

    @staticmethod
    def send_recovery_password_email(mail_to, context):
        html = render_to_string(EmailSender.RECOVERY_TEMPLATE, context=context)
        result = EmailSender.send_mail(mail_to, EmailSender.RECOVERY_SUBJECT, html)
        return result

    @staticmethod
    def send_mentor_score_email(mail_to, context):
        html = render_to_string(EmailSender.MENTOR_SCORE_TEMPLATE, context=context)
        result = EmailSender.send_mail(mail_to, EmailSender.MENTOR_SCORE_SUBJECT, html)
        return result
