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

@author: ymh
'''

import logging
import os

from django.conf import settings
from django.contrib.auth import get_user_model
from django.core import mail
from django.core.mail.message import EmailMultiAlternatives
from django.core.management.base import NoArgsCommand
from django.core.urlresolvers import set_script_prefix
from django.template.base import TemplateDoesNotExist
from django.template.loader import render_to_string
import premailer

from hdalab.models.renkan import HdalabRenkan


User = get_user_model()
logger = logging.getLogger(__name__)

TEMPLATE_NAME = "mails/moderation_notice"
class Command(NoArgsCommand):
    
    def handle_noargs(self, **options):
        # query renkan to moderate
        set_script_prefix(settings.SCRIPT_PREFIX)
        
        renkan_query = HdalabRenkan.objects.filter(state=HdalabRenkan.MODERATED)
        
        renkan_count = renkan_query.count()
        
        if renkan_count == 0:
            logger.info("Send moderation email : no renkan to moderate. exiting")
        logger.debug("Send moderation email : %d renkan(s) to moderate", renkan_count)
        
        renkan_list = list(renkan_query.select_related()[:20])
        
        connection = mail.get_connection()
        try:
            connection.open()
            for email_recipient in User.objects.filter(is_staff=True):
                if not email_recipient.email:
                    continue
    
                msg_html = ""
                msg_txt = ""
                try:
                    context = {
                        'renkan_count': renkan_count,
                        'renkan_list': renkan_list,
                        'WEB_URL': settings.WEB_URL,
                        'email_recipient': email_recipient
                    }
                    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 not found", TEMPLATE_NAME)
                    return
                except Exception as e:
                    logger.error("Error rendering template %s : %r", TEMPLATE_NAME, e)
                    raise e
        
                if not msg_html and not msg_txt:
                    logger.info("Send moderation email: nothing to email exiting")
                    continue
                emsg = EmailMultiAlternatives("Moderation Renkan", msg_txt, settings.DEFAULT_FROM_EMAIL, [email_recipient.email], connection=connection)
                emsg.attach_alternative(msg_html, "text/html")
                emsg.send(fail_silently=True)
        finally:
            connection.close()
    