# -*- coding: utf-8 -*-
'''
Created on Jul 17, 2014

@author: tc
'''
import logging
from renkanmanager.models import Renkan

from django.conf import settings
from django.core.mail import send_mail
from django.db import models
from django.db.models.signals import post_save
from django.template import loader
from django.template.base import TemplateDoesNotExist
from django.template.context import Context
from django.utils.translation import ugettext as _
from django.template.loader import render_to_string
from django.core.mail.message import EmailMultiAlternatives
from django.utils.html import strip_tags


logger = logging.getLogger(__name__)

class HdalabRenkan(models.Model):
    
    EDITION = 1
    MODERATED = 2
    PUBLISHED = 3
    REJECTED = 4
      
    STATE_CHOICES = (
    (EDITION, 'edition'),
    (MODERATED, 'moderated'),
    (PUBLISHED, 'published'),
    (REJECTED, 'rejected'),
    )
    
    STATE_CHOICES_DICT = {
        EDITION: _('edition_state'),
        MODERATED: _('moderated_state'),
        PUBLISHED: _('published_state'),
        REJECTED: _('rejected_state')
    }
    
    renkan = models.ForeignKey(Renkan, blank=False, null=False)
    state = models.IntegerField(choices=STATE_CHOICES, default=1)
    
    class Meta:
        app_label = 'hdalab'


class HdalabRenkanStateTransition(models.Model):

    renkan = models.ForeignKey(HdalabRenkan, blank=False, null=False)
    from_state = models.IntegerField(choices=HdalabRenkan.STATE_CHOICES, default=1, blank=False, null=False)
    to_state = models.IntegerField(choices=HdalabRenkan.STATE_CHOICES, default=1, blank=False, null=False)
    ts = models.DateTimeField(auto_now_add=True, blank=False, null=False)
    message = models.TextField(blank=True, null=True)
    author = models.ForeignKey(settings.AUTH_USER_MODEL, blank=False, null=False)
    
    class Meta:
        app_label = 'hdalab'

MAIL_TEMPLATES = {
    HdalabRenkan.PUBLISHED: ("mails/published_renkan", "Renkan publié"),
    HdalabRenkan.REJECTED: ("mails/rejected_renkan", "Renkan rejeté")
}


#TODO put into queue
def send_renkan_moderation_messages(sender, **kwargs):
    renkan_state = kwargs.get('instance', None)
    if not renkan_state or renkan_state.to_state not in MAIL_TEMPLATES:
        return

    msg_txt = ""
    msg_html = ""
    subject = ""
    try:
        template_name, subject = MAIL_TEMPLATES[renkan_state.to_state]
#        template = loader.get_template(template_name)
        context = {'renkan_state': renkan_state, 'WEB_URL': settings.WEB_URL}
        msg_html = render_to_string(template_name+".txt", context)
        msg_txt = render_to_string(template_name+".html", context)
    except TemplateDoesNotExist:
        logger.error("Mail template %s for state %s not found", MAIL_TEMPLATES[renkan_state.to_state], HdalabRenkan.STATE_CHOICES_DICT[renkan_state.to_state])
        return
    except Exception as e:
        logger.error("Error rendering template %s for state %s : %r", MAIL_TEMPLATES[renkan_state.to_state], HdalabRenkan.STATE_CHOICES_DICT[renkan_state.to_state], e)
    
    if msg_txt and msg_html and renkan_state.renkan and renkan_state.renkan.renkan and renkan_state.renkan.renkan.owner and renkan_state.renkan.renkan.owner.email:
        logger.debug("Sending following mail to %s : %s", renkan_state.renkan.renkan.owner.email, msg_txt)
        emsg = EmailMultiAlternatives(subject, strip_tags(msg_txt), settings.ADMINS[0][1], [renkan_state.renkan.renkan.owner.email])
        emsg.attach_alternative(msg_html, "text/html")
        emsg.send(fail_silently=True)


def queue_renkan_rendering(sender, **kwargs):
    pass
    #check state
    #queue renkan for endering
    
    
RENKAN_MODERATION_UUID = "e2f84503-609b-4efa-819d-908e2efe7b1b"
RENKAN_RENDERING_UUID = "b8830748-be2b-479a-8aef-c8d952437b2f"

post_save.connect(send_renkan_moderation_messages, sender=HdalabRenkanStateTransition, dispatch_uid=RENKAN_MODERATION_UUID)
