# -*- coding: utf-8 -*-
from __future__ import unicode_literals

from django.core.mail import EmailMessage
from django.core import mail
from django.conf import settings
import logging

log = logging.getLogger(__name__)

__all__ = ['BadgeEmail']


class BadgeEmail(object):
    @staticmethod
    def send_email(badge_id, users):
        from core.models import MailTemplate, Reporter
        email_messages = []
        for user in users:
            if isinstance(user, (int, long)):
                try:
                    user = Reporter.objects.get(pk=user)
                except Reporter.DoesNotExists:
                    log.critical('User with id=%s does not exist', user)
                    return
            template_code = 'badge.%s' % badge_id
            language = MailTemplate.LANGUAGE_RUSSIAN

            if user.is_russian_resident is False:
                language = MailTemplate.LANGUAGE_ENGLISH

            try:
                mail_template = MailTemplate.objects.get(code=template_code,
                                    language=language)
            except MailTemplate.DoesNotExist:
                log.critical('Not found mail template for badge.%s', badge_id)
                return
            subject = mail_template.subject
            template = mail_template.template.format(username=user.username)
            from_email = settings.FROM_EMAIL
            email_messages.append(
                EmailMessage(
                    subject=subject,
                    body=template,
                    from_email=from_email,
                    to=[user.email]
                )
            )
        connection = mail.get_connection(fail_silently=True)
        connection.send_messages(email_messages)
