#! /usr/bin/env python
# -*- coding: utf-8 -*-

# INSERT YOUR ADDRESS HERE
recipient = ["Nikolaus@rath.org"]

# Roundup boto uses several deprecated modules
import warnings
warnings.filterwarnings("ignore", "", DeprecationWarning, "roundup")

import sys
from roundup import instance
from roundup.date import Date,Interval
from roundup.mailer import Mailer
import quopri
from StringIO import StringIO

# open the instance
if len(sys.argv) != 2:
    print 'You need to specify an instance home dir'
instance_home = sys.argv[1]
instance = instance.open(instance_home)
db = instance.open('admin')

done_id = db.status.lookup("done")
waiting_id = db.status.lookup("waiting")
other_id = [x for x in db.status.list() if x != done_id]

# Determine current date, but with time 0:00:00
now = Date(Date(".").pretty('%Y-%m-%d'))

# Collect the Issues
issues = []
for kid in db.keyword.list():
    for sid in db.issue.filter(None, { "due_date": "-1m;6d",
                                       "keyword": kid,
                                       "status": other_id},
                               [ ("+", "due_date") ]):
        # Exclude issues which are still waiting for their
        # revival date
        if db.issue.get(sid, "status") == waiting_id and \
           not db.issue.get(sid, "superseder"):
            None # Do nothing
        else:
            issues.append( (sid,
                            db.keyword.get(kid, "name"),
                            db.issue.get(sid, "title"),
                            db.issue.get(sid, "due_date") - now ))

# Send Mail
if issues:
    body = StringIO()

    print >>body, "The following issues are due within the next 5 days.\n"
    print >>body, "%4s %-49s %-13s" % ("ID", "Title", "Due")
    print >>body, "-" * 68

    old = ""
    for issue in issues:
        id,keyword,title,date = issue
        if keyword != old:
            print >>body, "\n *** " + keyword + " ***"
            old = keyword

        print >>body, "%4s %-49s %-13s" % (id,title,date.pretty())


    mailer = Mailer(db.config)

    # To work around a Python bug, we had to change
    #self.smtp_send(to, str(message))
    # to
    #self.smtp_send(to, message.as_string(unixfrom=False))
    # in roundup/mailer.py, line 120 (in standard_message())
    mailer.standard_message(recipient, "Issues due within the next 5 days",
                            body.getvalue())

db.commit()
db.close()
