#!/usr/bin/env python

import harvest
from harvest.commands import init, init_demo, update
try:
    from collections import OrderedDict
except ImportError:
    from ordereddict import OrderedDict
from argparse import ArgumentParser, RawDescriptionHelpFormatter, PARSER


# http://stackoverflow.com/questions/13423540/argparse-subparser-hide-metavar-in-command-listing
class SubcommandHelpFormatter(RawDescriptionHelpFormatter):
    def _format_action(self, action):
        parts = super(RawDescriptionHelpFormatter, self)._format_action(action)
        if action.nargs == PARSER:
            parts = '\n'.join(parts.split('\n')[1:])
        return parts


# Top-level commands
commands = OrderedDict([
    ('init', init),
    ('init-demo', init_demo),
    ('update', update),
])

# Top-level argument parser
parser = ArgumentParser(description=harvest.__doc__,
    #usage='%(prog)s [options] <command> ...',
    version='Harvest v{0}'.format(harvest.__version__),
    epilog="See '%(prog)s <command> --help' for more information on a specific command.",
    formatter_class=SubcommandHelpFormatter)

parser.add_argument('--debug', action='store_true', help='Debug mode')

# Add sub-parsers for each command
subparsers = parser.add_subparsers(title='available commands',
    dest='command', metavar='<command>')

# Populate subparsers
for key in commands:
    module = commands[key]
    # Add it by name
    subparser = subparsers.add_parser(key, add_help=False, help=module.__doc__)
    # Update subparser with properties of module parser. Keep
    # track of the generated `prog` since it is relative to
    # the top-level command
    prog = subparser.prog
    subparser.__dict__.update(module.parser.__dict__)
    subparser.prog = prog

# Parse command-line arguments
options = parser.parse_args()

if options.debug:
    handler = commands[options.command].parser.handle_raw
else:
    handler = commands[options.command].parser.handle

# Get the module and call the main function
handler(options)
