# -*- coding: utf-8 -*-
__author__ = 'Arvin'
from django.core.management.base import BaseCommand
from django.core.mail.message import EmailMessage
from django.core.mail import get_connection
from django.template import loader
import json
import datetime
from ooredis import *
from base.email_setting import get_cfg_options
import os


def print_debug(msg):
    from mysite.settings import DEBUG
    if DEBUG:
        print msg
    pass


def send_email(subject, message, recipient_list, path=None,
               fail_silently=False, connection=None, content_subtype='html'):
    mail_cfg = get_cfg_options()
    connection = connection or get_connection(host=mail_cfg['email_host'],
                                              port=mail_cfg['email_port'],
                                              username=mail_cfg['email_host_user'],
                                              password=mail_cfg['email_host_password'],
                                              use_tls=mail_cfg['email_use_tls'],
                                              fail_silently=fail_silently)
    try:
        em = EmailMessage(subject, message, mail_cfg['sender_name'], recipient_list, connection=connection)
        if path:
            print_debug("[*]File path %s" % path)
            em.attach_file(path)
        em.content_subtype = content_subtype
        ret = em.send()
    except Exception, e:
        import time
        print_debug("[*]Send Email Error: %s" % e)
        ret = 0
        time.sleep(60)
    return ret


def file_rename(path):
    from django.utils.translation import ugettext
    import os
    import datetime
    if path:
        now = datetime.datetime.now()
        filename = path.replace('\\', '/').split('/')[-1]
        new_file_path = path.replace(filename, ugettext(u'考勤异常(%s).xls') % now.strftime('%Y-%m-%d')).encode('gb18030')
        if os.path.exists(new_file_path):
            os.rename(new_file_path)
        os.rename(path, new_file_path)
        path = new_file_path
    return path


def email_handle():
    import time
    r_client = get_client()
    while True:
        try:
            emails = r_client.keys('email:*:detail')
            if emails:
                for email in emails:
                    email = Dict(email)
                    try:
                        subject = email['subject']
                        receiver = email['receiver']
                        email_template = email['email_template']
                        path = email['path']
                        path = file_rename(path)
                        params = json.loads(email['params'])
                        if path:
                            ret = send_email(subject, params, [receiver], path=path, content_subtype='plain')
                        else:
                            context = loader.render_to_string(email_template, params)
                            ret = send_email(subject, context, [receiver], path=path)
                    except ValueError, e:
                        print_debug("[*]Email Parse Error: %s -->(Subject:%s, Params:%s, Receiver:%s, Path:%s) " %
                                    (e, email['subject'], email['params'], email['receiver'], email['path']))
                        email.delete()
                        continue
                    if ret:
                        email.delete()
                        if path:
                            os.remove(path)
                        print_debug("[*]Send success %s email(s), Receiver:%s" % (ret, receiver))
                    else:
                        print_debug("[*]Email exception [subject]: %s [receiver]: %s  [time]:%s" % (subject, receiver, datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')))
            time.sleep(1)
        except Exception, e:
            print_debug("[*]Email Handle Error: %s " % e)
            time.sleep(30)


class Command(BaseCommand):
    option_list = BaseCommand.option_list + ()
    help = "Start email sending process."
    args = ''

    def handle(self, *args, **options):
        email_handle()