#!/usr/bin/env python3

# http://inamidst.com/saxo/
# Created by Sean B. Palmer

import calendar
import datetime
import random
import re
import time

import saxo

months = "(?:Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)"
r_arg = re.compile("(\d?\d %s)(?: (.*))?$" % months)

@saxo.pipe
def main(arg):
    if not arg:
        return "Set a reminder at a certain time. Must match " + r_arg.pattern

    match = r_arg.match(arg)
    if not match:
        return "Sorry, input must match " + r_arg.pattern

    now = datetime.datetime.now()
    t = datetime.datetime.strptime(match.group(1), "%d %b")
    t = t.replace(hour=8)
    t = t.replace(year=now.year)
    t = t.replace(second=random.randint(0, 59))
    if t < now:
        t = t.replace(year=t.year + 1)

    message = match.group(2)
    unixtime = calendar.timegm(t.utctimetuple())

    nick = saxo.env("nick")
    sender = saxo.env("sender")

    if not (nick or sender):
        return "Sorry, couldn't set a reminder!"

    if message:
        message = nick + ": " + message
    else:
        message = nick + "!"

    args = (unixtime, "msg", (sender, message))
    saxo.client("schedule", *args)

    when = time.strftime("%d %b %Y %H:%M:%S UTC", time.gmtime(unixtime))
    return "%s: Will remind at %s" % (nick, when)
