from gozerbot.commands import cmnds
from gozerbot.examples import examples
from gozerbot.periodical import at, periodical
from gozerbot.plugins import plugins
import copy
import datetime
import types

class AtJob:
    def __init__(self, when, bot, nevent):
        self.when = when
        self.bot  = bot
        self.nevent = nevent

        @at(when)
        def at_job():
            plugins.trydispatch(self.bot, self.nevent)
        at_job.cmnd = self.nevent.txt
        at_job.ievent = self.nevent
        at_job()

def handle_at(bot, ievent):
    """ start a job at a certain time """
    if len(ievent.args) < 2:
        ievent.missing('<time> <command>')
        return
    nevent = copy.copy(ievent)
    nevent.txt = ' '.join(ievent.args[1:])
    if plugins.woulddispatch(bot, nevent):
        try:
            when = int(ievent.args[0])
        except ValueError, e:
            when = ievent.args[0] 
        AtJob(when, bot, nevent)
        ievent.reply('job scheduled')
    else:
        ievent.reply('could not dispatch')

cmnds.add('at', handle_at, 'USER')
examples.add('at', 'start a job at given time', 'at 11:00 say moooo')

def handle_atlist(bot, ievent):
    """ show scheduled at events """
    reply = []
    for job in periodical.jobs:
        if job.func.func_name != 'at_job':
            continue
        next = job.next
        if type(next) in [types.FloatType, types.IntType]:
            next = datetime.datetime(*time.localtime(next)[:7])
        try:
            cmnd = job.func.cmnd
        except AttributeError:
            cmnd = '<unknown>'
        reply.append('%d: at %s, "%s"' % (job.id(), next, cmnd)) 
    if reply:
        ievent.reply(reply, dot=True)
    else:
        ievent.reply('no jobs')

cmnds.add('at-list', handle_atlist, 'OPER')

