# -*- coding: utf-8 -*-
'''
Created on Mar 8, 2015

@author: ymh
'''
import logging
import os
from renkanmanager.models import Renkan

from django.conf import settings
from django.core.mail.message import EmailMultiAlternatives
from django.db.models.signals import post_save, pre_delete
from django.template.base import TemplateDoesNotExist
from django.template.loader import render_to_string
import premailer

from hdalab.models.renkan import HdalabRenkan, HdalabRenkanStateTransition


logger = logging.getLogger(__name__)

MAIL_TEMPLATES = {
    (HdalabRenkan.MODERATED,HdalabRenkan.PUBLISHED): ("mails/published_renkan", "Renkan publié"),
    (HdalabRenkan.MODERATED,HdalabRenkan.REJECTED): ("mails/rejected_renkan", "Renkan rejeté"),
    (HdalabRenkan.PUBLISHED, HdalabRenkan.EDITION): ("mails/unpublished_renkan", "Renkan dépublié"),
    (HdalabRenkan.PUBLISHED, 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.from_state,renkan_state.to_state) not in MAIL_TEMPLATES:
        return

    template_key = (renkan_state.from_state,renkan_state.to_state)
    msg_txt = ""
    msg_html = ""
    subject = ""
    try:
        template_name, subject = MAIL_TEMPLATES[template_key]
#        template = loader.get_template(template_name)
        context = {'renkan_state': renkan_state, 'WEB_URL': settings.WEB_URL}
        msg_html = premailer.transform(render_to_string(template_name+".html", context), base_url=os.path.join(settings.STATIC_ROOT,'site'))
        msg_txt = render_to_string(template_name+".txt", context)
    except TemplateDoesNotExist:
        logger.error("Mail template %s for state %s not found", MAIL_TEMPLATES[template_key], 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[template_key], HdalabRenkan.STATE_CHOICES_DICT[renkan_state.to_state], e)
#        return
#        raise 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, msg_txt, settings.DEFAULT_FROM_EMAIL, [renkan_state.renkan.renkan.owner.email])
        emsg.attach_alternative(msg_html, "text/html")
        emsg.send(fail_silently=True)


def queue_renkan_rendering(sender, **kwargs):
    renkan_state = kwargs.get('instance', None)
    if not renkan_state:
        return
    
    if renkan_state.from_state == HdalabRenkan.PUBLISHED and renkan_state.renkan.renkan.image != settings.DEFAULT_RENKAN_ICON:
        if renkan_state.renkan.renkan.image:
            renkan_state.renkan.renkan.image.delete(False)
            renkan_state.renkan.renkan.image.delete_thumbnails()
        renkan_state.renkan.renkan.image = settings.DEFAULT_RENKAN_ICON
        renkan_state.renkan.renkan.save()
    elif renkan_state.to_state == HdalabRenkan.PUBLISHED:
        from hdalab.tasks import capture_preview
        capture_preview.delay(renkan_state.renkan.renkan.rk_id)  # @UndefinedVariable

def renkan_delete_image(sender, **kwargs):
    renkan = kwargs.get('instance', None)
    if not renkan or not renkan.image or renkan.image == settings.DEFAULT_RENKAN_ICON:
        return
    renkan.image.delete(False)
    renkan.image.delete_thumbnails()

    
RENKAN_MODERATION_UUID = "e2f84503-609b-4efa-819d-908e2efe7b1b"
RENKAN_RENDERING_UUID = "b8830748-be2b-479a-8aef-c8d952437b2f"
RENKAN_DELETE_UUID = "09c23ca2-4d59-4c29-b94a-2c2672d5a89b"

post_save.connect(send_renkan_moderation_messages, sender=HdalabRenkanStateTransition, dispatch_uid=RENKAN_MODERATION_UUID)
post_save.connect(queue_renkan_rendering, sender=HdalabRenkanStateTransition, dispatch_uid=RENKAN_RENDERING_UUID)
pre_delete.connect(renkan_delete_image, sender=Renkan, dispatch_uid=RENKAN_DELETE_UUID)

