#! /usr/bin/env python
"""Qonos.

Usage:
    qonos [options] <command> [<args>...]
    qonos [--help]

The most commonly used qonos commands are:
    get-schedule <schedule-id>
    list-schedules
    create-schedule <request-body>
    delete-schedule

    get-job <job-id>
    list-jobs
    create-job <request-body>
    delete-job

    get-worker <worker-id>
    list-workers
    create-worker <request-body>
    delete-worker

Options:
    --version   Show version.
    --host=<url>      Api endpoint.
    --port=<port>     Api port.
"""

"""
This script is meant to be a *very* lightweight cli interface into the
qonosclient and should not have deep working knowledge of the system.

It works by calling the function of the client with the same name as <command> and
passing all arguments giving as arguments and options following the command as
kwargs to the function.
"""

import inspect
import os
import sys

#TODO(ameade): find better way to add to sys.path
# If ../../../qonos/__init__.py exists, add ../../../../ to Python search path, so that
# it will override what happens to be installed in /usr/(local/)lib/python...
possible_topdir = os.path.normpath(os.path.join(os.path.abspath(sys.argv[0]),
                                   os.pardir,
                                   os.pardir,
                                   os.pardir,
                                   os.pardir))
if os.path.exists(os.path.join(possible_topdir, 'qonos', '__init__.py')):
    sys.path.insert(0, possible_topdir)

from docopt import docopt
try:
    import json
except ImportError:
    import simplejson as json

from qonos.qonosclient import client


def _get_kwargs(args):
    """Parse the keyword arguments out of the command options."""
    kwarg_list = [arg for arg in args if arg.startswith("--")]
    kwargs = {}
    for kwarg in kwarg_list:
        key, value = kwarg[2:].split("=")
        kwargs[key] = value
    return kwargs


def do_command(args):
    host = args.get('--host') or os.environ.get('QONOS_HOST', 'localhost')
    port = args.get('--port') or os.environ.get('QONOS_PORT', 8080)
    qonosclient = client.create_client(host, port)


    #Find the function to call
    cmd = args['<command>']
    command = cmd.replace('-', '_')
    if hasattr(qonosclient, command):
        function = getattr(qonosclient, command)
    elif cmd == 'help':
        exit(__doc__)
    else:
        exit("%r is not a qonos command. See 'qonos help'." % cmd)

    #call the function
    function_args = [arg for arg in args['<args>'] if not arg.startswith("--")]
    function_kwargs = _get_kwargs(args['<args>'])
    if function_args and function_args[0] == 'help':
        print("This command has the following arguments:")
        print(inspect.getargspec(function).args[1:])
    else:
        results = function(*function_args, **function_kwargs)
        print json.dumps(results, indent=4)


if __name__ == '__main__':
    args = docopt(__doc__,
                  version='Qonos 0.1',
                  options_first=True)
    do_command(args)
