#!/usr/bin/env python
"""
Command Log. Or Captain's Log.
"""
import sys

import logging
log = logging.getLogger('clog')

from optparse import OptionParser, OptionGroup

from clog import model
Session = model.Session

from clog import actions

import os
from sqlalchemy import create_engine

def main():
    usage="%prog [OPTIONS] [TAG [VALUE]]\n" + __doc__

    # FIXME: Use argparse someday
    parser = OptionParser(usage)
    parser.add_option("--export-json", dest="export_json", action="store_true", help="Export data into a list of JSON objects to STDOUT.")
    parser.add_option("--import-json", dest="import_json", action="store_true", help="Import data from a list of JSON objects from STDIN.")
    parser.add_option("--pipe", "-p", dest="pipe", action="store_true", help="Read VALUE from STDIN.")
    parser.add_option("--filter", "-f", dest="filter", metavar="TAG", help="Filter clog entries by tag.")
    parser.add_option("--verbose", "-v", dest="verbose", action="count", help="Enable verbose output. Use twice to enable debug output.")

    tag_group = OptionGroup(parser, "TAG")
    tag_group.add_option("--timestamp", dest="timestamp", metavar="TIMESTAMP", help="Date and time, absolute or relative human format. Examples: 1985-11-30 12:00:00, 2pm, nov 30")
    parser.add_option_group(tag_group)

    options, args = parser.parse_args()

    if options.verbose > 1:
        log.setLevel(logging.DEBUG)
    elif options.verbose > 0:
        log.setLevel(logging.INFO)

    db_path = os.path.expanduser('~/.clog')
    try:
        os.mkdir(db_path)
    except OSError, e:
        # Already exists
        pass

    engine = create_engine("sqlite:///" + db_path + '/db.sqlite')
    model.init_model(engine)
    model.metadata.create_all(bind=engine)

    if options.export_json:
        return actions.export_json_entries(options, args)
    elif options.import_json:
        return actions.import_json_entries(options, args)

    if args:
        return actions.add_entry(options, args)
    else:
        return actions.view_recent(options, args)


if __name__ == '__main__':
    log_handler = logging.StreamHandler()
    log_handler.setFormatter(logging.Formatter('%(levelname)-8s %(message)s'))
    log.addHandler(log_handler)

    n = main()
    if n:
        sys.exit(n)
