#!/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"
__created__ = "18 January 2008"
__rcsid__ = "$Id: nl_date 802 2008-06-06 18:15:21Z dang $"

import logging
import magicdate
from optparse import OptionParser
import re
import sys
import time
#
from netlogger.parsers.base import parseDate
from netlogger.nlapi import formatDate
from netlogger import util

ASCII_DATE = re.compile("\d\d\d\d-\d\d-\d\dT\d\d:\d\d:\d\d\.?")
FLOAT_DATE = re.compile("\d{10,14}\.?\d*")

def main():    
    parser = OptionParser(usage="%prog [options]", version="1.0")
    parser.add_option('-d', '--date', dest='date', type='string', 
                      default=None, 
                      help="convert the given date, "
                       "which may be a fuzzy date like 'now', "
                      "'yesterday', or '1 week ago', "
                      "as well as YYYY-MM-DD notation")
    parser.add_option('-s','--seconds', dest='sec', type='float',
                      default=None,
                      help="convert from this number of seconds since the "
                      "UNIX epoch (1970-01-01T00:00:00Z)")
    parser.add_option('-z', '--utc', dest='utc', action='store_true',
                      help="interpret given date or default 'now' as "
                      "being in UTC instead of the local timezone")

    (options, args) = parser.parse_args()
    if options.date is None and options.sec is None:
        options.date = 'now'
    if options.date is not None:
        if options.utc:
            tz = 'Z'
        else:
            tz = util.tzstr()
        if ASCII_DATE.match(options.date):
            iso = options.date
        else:
            try:
                iso = magicdate.magicdate(options.date).isoformat()
            except:
                parser.error("sorry, I can't parse '%s' as a date" % 
                             options.date)
            print "%s =>" % options.date,
        # add 'midnight' time if none given
        if 'T' not in iso:
            iso += 'T00:00:00'
        # only append timezone if none is there already
        if not iso.endswith('Z') and not re.match('.*[+-]\d\d:\d\d$', iso):
            iso += tz
        print "%s => %lf" % (iso, parseDate(iso))
    if options.sec is not None:
        print "%lf => %s" % (options.sec, formatDate(options.sec))

if __name__ == "__main__":
    main()                                                       
