#!/usr/bin/env python

# bugzilla - a command line interface to Bugzilla
# Copyright (C) 2011, 2012 Benon Technologies Pty Ltd
# Copyright (C) 2011, 2012 Fraser Tweedale
#
# bugzillatools is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.


import argparse

import bzlib.command
import bzlib.config
import bzlib.ui

# retrieve user-defined aliases
conf = bzlib.config.Config.get_config('~/.bugzillarc')
if conf.has_section('alias'):
    aliases = dict(conf.items('alias'))
else:
    aliases = {}

# format the epilogue
epilog = None
lines = map(
    lambda (alias, target): "    {:20}{}".format(alias, target),
    aliases.viewitems()
)
epilog = 'user-defined aliases:\n' + '\n'.join(lines) if lines else None

# create an argument parser
_parser = argparse.ArgumentParser(add_help=False)

# add global arguments
_parser.add_argument('-V', action='version',
    version='%(prog)s {}'.format(bzlib.version))

# parse known args
args, argv = _parser.parse_known_args()

# add subcommands
parser = argparse.ArgumentParser(
    parents=[_parser],
    description='Interact with Bugzilla servers.',
    epilog=epilog,
    formatter_class=argparse.RawDescriptionHelpFormatter
)
subparsers = parser.add_subparsers(title='subcommands')
commands = {x.__name__.lower(): x for x in bzlib.command.commands}
for name, command in sorted(commands.viewitems(), key=lambda x: x[0]):
    command_parser = subparsers.add_parser(name,
        formatter_class=argparse.RawDescriptionHelpFormatter,
        help=command.help(), epilog=command.epilog())
    map(lambda x: x(command_parser), command.args)
    command_parser.set_defaults(command=command)

# process user-defined aliases
for i, arg in enumerate(argv):
    if arg in aliases:
        # an alias; replace and stop processing
        argv[i:i+1] = aliases[arg].split()
        break
    if arg in commands:
        # a valid command; stop processing
        break

# parse remaining args
args = parser.parse_args(args=argv, namespace=args)

# execute command
ui = bzlib.ui.UI()
args.command(args, parser, commands, aliases, ui)()
