#!/usr/bin/env python
## Copyright (c) 2004, The Regents of the University of California, through
## Lawrence Berkeley National Laboratory (subject to receipt of any required
## approvals from the U.S. Dept. of Energy).  All rights reserved.
"""
NetLogger date-formatting utility
"""
__author__ = "Dan Gunter dkgunter@lbl.gov"
__rcsid__ = "$Id: nl_date 23923 2009-09-18 22:42:26Z ksb $"

import sys

from netlogger import nldate
from netlogger.nllog import OptionParser, get_logger

def main():
    desc = "Parse the given ISO8601 or plain English date(s) " \
           "to seconds since the epoch or, " \
           "if the date is seconds since the epoch, format it to an "\
           "ISO8601 date string. " \
           "If no date is given, assume 'now'."
    parser = OptionParser(usage="%prog [dates...]", description=desc)
    parser.add_option('-u',  dest='utc_in', action='store_true',
                      default=False,
                      help="interpret given date or default 'now' as "
                      "being in UTC (default=False, local timezone). ")
    parser.add_option('-U', dest='utc_out', action='store_true',
                      default=False,
                      help="show result in UTC (default=False, local timezone)")
    (options, args) = parser.parse_args()
    log = get_logger(__file__)  # Should be first done, just after parsing args
    if not args:
        dates = ('now',)
    else:
        dates = args
    gmt_kw = dict(is_gmt=options.utc_in, set_gmt=options.utc_out)
    log.info("run.start")
    for date in dates:
        log.debug("convert.start", value=date)
        status = 0
        type, result = nldate.guess(date, **gmt_kw)
        if type == nldate.SECONDS:
            if options.utc_out:
                iso_date = nldate.utcFormatISO(result)
            else:
                iso_date = nldate.localtimeFormatISO(result)
            print "%s => %s" % (date, iso_date)
        elif type == nldate.ENGLISH:
            if options.utc_in:
                parser.error("Plain English date '%s' can only "
                        "refer to local time" % (date))
            isodate = nldate.makeISO(date, **gmt_kw)
            print "%s => %s => %s" % (date, isodate, result)
        elif type == nldate.ISO8601:
            if len(date) >= len("2000-01-01T12:34:56"):
                print "%s => %s" % (date, result)
            else:
                full_date = nldate.completeISO(date, **gmt_kw)
                print "%s => %s => %s" % (date, full_date, result)
        elif type == nldate.UNKNOWN:
            log.warn("convert.unknown", input__value=date)
            status = 1
        else:
            log.error("convert.error", input__value=date, type=type)
            status = -1
        log.debug("convert.end", status=status)
    log.info("run.end", status=0)

if __name__ == "__main__":
    sys.exit(main())
