#!/usr/bin/python2
# -*- coding: utf-8 -*-

import argparse
import calendar
import smtplib
import sys
import codecs

from datetime import datetime
from email.mime.text import MIMEText
from email.header import Header
from email import charset


def createMail(args, target_date, diff):
    fvars = {"date": target_date.strftime("%d.%m.%Y"), "diff":diff.days}
    body = codecs.open(args.msg_template, 'r', "utf-8").read() % fvars

    msg = MIMEText(body, _charset="UTF-8")

    msg['Subject'] = Header(args.subject, "utf-8") % fvars
    msg['From'] =  args.From
    msg['To'] = args.to
    return msg


def getNextCleaningDate(cal, args):
    if args.first:
        my_cal = cal
    else:
        my_cal = reversed(cal)

    for week in my_cal:
        if week[args.day] != 0:
            return week[args.day]


def main(args):
    today = datetime.today()
    cal = calendar.monthcalendar(today.year, today.month)

    target_day = getNextCleaningDate(cal, args)
    target_date = datetime(today.year, today.month, target_day)
    diff = target_date - today

    print("target_day", target_day)
    print("target_date", target_date)
    print("diff", diff)

    if diff.days in args.reminder_days:
        charset.add_charset('utf-8', charset.QP, charset.QP)
        msg = createMail(args, target_date, diff)
        print(type(msg.as_string()))
        print("msg", msg.as_string())

        if args.debug:
            return

        s = smtplib.SMTP(args.host)
        s.set_debuglevel(3)
        s.sendmail(args.From, [args.to], msg.as_string())
        s.quit()


if __name__ == '__main__':
    parser = argparse.ArgumentParser(description="The ctdo configurable mail reminder script. " \
        "Works on the last given day in month. Sends a mail with given " \
        "'msg_template' if today is a day in the list of 'reminder_days'")

    parser.add_argument('-d', "--day", type=int, choices=range(7), required=True, help="which last day in month? monday=0, tuesday=1, ...")
    parser.add_argument('-r', "--reminder_days", type=int, action="append", choices=range(0, 31), required=True, help="on which day to remind the crowd? 1 will be one day before, 7 a week before. May be specified multiple times.")
    parser.add_argument('-m', "--msg_template", required=True, help="The path to a a file with predefined email text to send. You can use %%(date)s and %%(diff) variables in the text.")
    parser.add_argument('-s', "--subject", default="Das bissken Haushalt aka Aufräumtag im CTDO", help="mail subject")
    parser.add_argument('-f', "--From", default="CTDOReminder <discuss@lists.chaostreff-dortmund.de>", help="mail from")
    parser.add_argument('-t', "--to", default="discuss@lists.chaostreff-dortmund.de", help="mail to")
    parser.add_argument('-H', "--host", default="", help="the smtp server to send to")
    parser.add_argument('-D', "--debug", action="store_true", help="don't send the mail")
    parser.add_argument('-F', "--first", action="store_true", help="take the first instead of last")

    args = parser.parse_args(sys.argv[1:])

    main(args)
