#!/usr/bin/python
# -*- coding: UTF-8 -*-
#
# Copyright (c) 2007 Tarek Ziadé
#
# Authors:
#   Tarek Ziadé <tarek@ziade.org>
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
from datetime import datetime
from base64 import b64encode

from model import mailed_data, mail_data

def send_mail(sender, recipients, subject, msg):
    """sends the mail by storing it into the DB"""
    inserter = mail_data.insert()
    if isinstance(msg, unicode):
        msg = msg.encode('utf8')
    if isinstance(subject, unicode):
        subject = subject.encode('utf8')

    res = inserter.execute(subject=subject, sender=sender,
                          recipients=','.join(recipients),
                          data=b64encode(msg), date=datetime.now())

    return res.last_inserted_ids()[0]

def mail_status(mail_id=None):
    """getting mail status"""
    def _small(mail):
        return {'subject': mail.subject, 'date': mail.date,
                'status': mail.status}

    if mail_id is None:
        return [_small(mail) for mail in
                mailed_data.select().execute()]

    res = mailed_data.select().execute(original_id=mail_id).fetchall()
    if len(res) == 0:
        # still in queue
        return u'processing'
    return res[0].status

def mail_queue_size():
    """return the queue size"""
    return len(mail_data.select().execute().fetchall())

