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

import logging

from django.db import models
from django.db.models.signals import post_save
from django.utils.encoding import python_2_unicode_compatible
from django.utils.translation import ugettext_lazy as _


__all__ = ['MailTemplate']

logger = logging.getLogger(__name__)


@python_2_unicode_compatible
class MailTemplate(models.Model):

    class Meta:
        app_label = 'core'
        unique_together = ('code', 'language')


    LANGUAGE_RUSSIAN = 0
    LANGUAGE_ENGLISH = 1

    LANGUAGES = (
        # Translators: EN russian
        (LANGUAGE_RUSSIAN, _('language.russian')),
        # Translators: EN english
        (LANGUAGE_ENGLISH, _('language.english')),
    )

    TRANSLATABLE_FIELDS = {'subject', 'template'}
    TANKER_TYPE = 'mailtemplate'

    code = models.CharField(max_length=100, default="")
    subject = models.CharField(max_length=255,  default="")
    language = models.IntegerField(choices=LANGUAGES, default=LANGUAGE_RUSSIAN)
    template = models.TextField(default="")
    created = models.DateTimeField(auto_now_add=True)
    modified = models.DateTimeField(auto_now=True)

    def __str__(self):
        return self.code

    def get_tanker_language_code(self):
        if self.language == self.LANGUAGE_RUSSIAN:
            return 'ru'
        elif self.language == self.LANGUAGE_ENGLISH:
            return 'en'
        raise Exception('Forgotten Language')


    @classmethod
    def get_language_code(cls, language):
        if language == 'ru':
            return cls.LANGUAGE_RUSSIAN
        if language == 'en':
            return cls.LANGUAGE_ENGLISH
        logger.critical("No language code for language: %s", language)
        return cls.LANGUAGE_ENGLISH

def create_mail_template_with_other_language(sender, instance, **kwargs):
    if instance.language == MailTemplate.LANGUAGE_RUSSIAN:
        new_language = MailTemplate.LANGUAGE_ENGLISH
    else:
        new_language = MailTemplate.LANGUAGE_RUSSIAN
    obj, created = MailTemplate.objects.get_or_create(
        code=instance.code,
        language=new_language,
        defaults={'subject': instance.subject})

post_save.connect(create_mail_template_with_other_language, sender=MailTemplate)
