#!/usr/bin/env python
# -*- encoding: utf-8 -*-
from __future__ import unicode_literals, print_function

import os.path
import sys

from gocd_cli import utils


def usage():
    print('usage: {0} <command> <subcommand> [<posarg1>, ...] [--kwarg1=value, ...]'.format(
        os.path.basename(sys.argv[0])
    ))
    print('Commands:')
    print('{0:3}{1}'.format('', 'help <command> [subcommand]'))
    for command in utils.list_commands():
        module = utils.get_command_module(command)
        print_command_documentation(command, module)


def print_command_documentation(command, module, extended_help=False):
    first = True
    print('{0:3}{1}'.format('', command))
    for subcommand in module.__all__:
        cmd = getattr(module, subcommand)

        if extended_help:
            if not first:
                print('{0:7}--'.format(''))

            for line in cmd.get_usage().split('\n'):
                print('{0:7}{1}'.format('', line.rstrip()))
        else:
            print('{0:7}{1}: {2}'.format(
                '',
                utils.dasherize_name(subcommand),
                cmd.get_usage_summary()
            ))

        first = False


if __name__ == '__main__':
    if len(sys.argv) < 3:
        usage()
        sys.exit(1)
    elif sys.argv[1] == 'help':  # XXX: This entire thing is pretty shoddy, but it works.
        module_name = sys.argv[2]
        module = __import__('gocd_cli.commands', fromlist=(module_name,))
        if len(sys.argv) == 4:
            command_name = sys.argv[3]
            cmd = getattr(getattr(module, module_name), utils.classify_name(command_name))
            print(cmd.get_usage())
        else:
            print_command_documentation(module_name, getattr(module, module_name), True)
    else:
        command, subcommand = sys.argv[1:3]
        server = utils.get_go_server()
        result = utils.get_command(server, *sys.argv[1:]).run()

        # TODO: Add some tests for this, when the integration suite is in place \o/
        response = getattr(result, 'get', None)
        if response:
            exit_code = response('exit_code', 0)
            output_obj = sys.stderr if exit_code > 0 else sys.stdout

            print(response('output', 0), file=output_obj)
            exit(exit_code)
