#!/usr/bin/python
# -*- python -*-

import sys
import time 
from optparse import OptionParser

from twisted.internet import reactor, defer
from twisted.python import log

from smap import loader, util
from smap.contrib import dtutil

def get_parser():
    usage = 'usage: %prog [options] conf-file <paths ...>'
    parser = OptionParser(usage=usage)
    parser.add_option('-t', '--timefmt', dest='timefmt', default='%m-%d-%Y',
                      type='str', 
                      help='time format string for start and end ("%m-%d-%Y")')
    parser.add_option('-s', '--start-time', dest='start_time', 
                      default=str(int(time.time()) - 3600), type='str',
                      help='start time of import (1 hour ago)')
    parser.add_option('-e', '--end-time', dest='end_time',
                      default=str(int(time.time())), type='str',
                      help='end time of import (now)')
    parser.add_option('-z', '--timezone', dest='timezone',
                      default='Local', type='str',
                      help='time zone for time conversion')
    parser.add_option('-r', '--reset', dest='reset',
                      default=False, action='store_true',
                      help='reset drivers before running')
    parser.add_option('-n', '--no-cache', dest='cache',
                      default=True, action='store_false',
                      help='don\'t cache downloaded data')
    return parser


if __name__ == '__main__':
    p = get_parser()
    opts, args = p.parse_args()
    if len(args) < 1:
        p.error("conf file is a required argument")

    log.startLogging(sys.stdout)
    sections = map(util.norm_path, args[1:])
    inst = loader.load(args[0], sections=sections)

    for dpath, driver in inst.drivers.iteritems():
        if len(sections) > 1 and not dpath in sections:
            continue

        if not hasattr(driver, "load"):
            log.err('Error: driver does not have "load" method')
            sys.exit(1)

        if hasattr(driver, 'reset') and \
                callable(driver.reset) and \
                opts.reset:
            log.msg("Resetting driver")
            driver.reset()

    st = dtutil.strptime_tz(opts.start_time, opts.timefmt, opts.timezone)
    et = dtutil.strptime_tz(opts.end_time, opts.timefmt, opts.timezone)
    print st, et

    dl = []
    for dpath, driver in inst.drivers.iteritems():
        if len(sections) > 1 and not dpath in sections:
            continue
        try:            
            d = driver.load(st, et, cache=opts.cache)
        except TypeError:
            d = driver.load(st, et)
        d.addCallback(lambda x: inst._flush())
        dl.append(d)
    dl = defer.DeferredList(dl, consumeErrors=True)
    dl.addCallbacks(lambda x: reactor.stop())
    reactor.run()
