#!/usr/bin/env python
# -*- coding: utf-8 -*-
# $Id: __init__.py 9476 2015-11-10 08:55:23Z Judy $
#
# Copyright (c) 2015 Nuwa Information Co., Ltd, All Rights Reserved.
#
# Licensed under the Proprietary License,
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at our web site.
#
# See the License for the specific language governing permissions and
# limitations under the License.
#
# $Author: Judy $ (last)
# $Date: 2015-11-10 16:55:23 +0800 (Tue, 10 Nov 2015) $
# $Revision: 9476 $
"""
Celery tasks which should be run at cloud worker.
"""

import os
import time
import datetime
import logging

from django_ses import SESBackend

from Iuppiter.Encoding import utf8

from Iuno.cloud.queue.App import app

logger = logging.getLogger(__name__)

@app.task
def send(email_messages, fail_silently=False, *args, **kws):
    """
    Send email via SES backend.

    @param email_messages Email messages passed to backend.
    @param fail_silently See EmailBackend.
    @param *args Arguments passed to EmailBackend.
    @param *kws Keyword arguments passed to EmailBackend.
    @return Number of messages sent.
    """
    sender = SESBackend(fail_silently, *args, **kws)
    sentNum = sender.send_messages(email_messages)

    # Retain sent messages.
    finishTimeStamp = time.time()
    finishDateTime = datetime.datetime.fromtimestamp(finishTimeStamp)
    folderName = finishDateTime.strftime('%Y-%m-%d')
    folderPath = os.path.join('sent', folderName)
    if not os.path.exists(folderPath):
        os.makedirs(folderPath)

    sesExtra = []

    n = 0
    for message in email_messages:
        extraHeaders = message.extra_headers
        sesExtra.append({
            'message_id': extraHeaders['message_id'],
            'request_id': extraHeaders['request_id'],
        })

        try:
            while True:
                n += 1
                fileName = '%ld_%d.html' % (finishTimeStamp, n)
                path = os.path.join(folderPath, fileName)
                if not os.path.exists(path):
                    with open(path, 'wb') as f:
                        f.write(utf8(message.body))

                    logger.info(('EMail sent [FROM]: %s [TO]: %s '
                                 '[SUBJECT]: %s [BODY HTML]: %s') % (
                                message.from_email, message.recipients(),
                                message.subject, fileName))
                    break
        except Exception, e:
            try:
                logger.debug(('EMail sent [FROM]: %s [TO]: %s '
                              '[SUBJECT]: %s [BODY HTML]: FAILED => %s.') % (
                             message.from_email, message.recipients(),
                             message.subject, str(e)))
            except:
                continue

    return sentNum, sesExtra
