#! /usr/bin/env python

"""
This is the MoltenIron Command Line client that speaks to
a MoltenIron server.
"""

# Copyright (c) 2016 IBM Corporation.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#    http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
# implied.
# See the License for the specific language governing permissions and
# limitations under the License.

# pylint: disable-msg=C0103
# pylint: disable=redefined-outer-name

import argparse
import json
import os
import sys

from pkg_resources import resource_filename
import yaml

from molteniron import molteniron


if __name__ == "__main__":
    mi = molteniron.MoltenIron()

    parser = argparse.ArgumentParser(description="Molteniron CLI tool")
    parser.add_argument("-c",
                        "--conf-dir",
                        action="store",
                        type=str,
                        dest="conf_dir",
                        help="The directory where configuration is stored")

    parser.add_argument("-o",
                        "--output",
                        action="store",
                        type=str,
                        default="json",
                        dest="output",
                        help="The output should be json (the default)"
                             " or result (only the result string)")

    subparsers = parser.add_subparsers(help="sub-command help")

    # Register all decorated class functions by telling them argparse
    # is running
    for (cmd_name, cmd_func) in list(molteniron.command.all.items()):
        func = getattr(mi, cmd_name)
        func(subparsers=subparsers)  # Tell the function to setup for argparse

    args = parser.parse_args()

    output = args.output.upper().lower()
    if output == "json":
        pass
    elif output == "result":
        pass
    else:
        parser.error("Unknown output type %s" % (output, ))

    if args.conf_dir:
        if not os.path.isdir(args.conf_dir):
            msg = "Error: %s is not a valid directory" % (args.conf_dir, )
            print(msg, file=sys.stderr)
            sys.exit(1)

        YAML_CONF = os.path.realpath("%s/conf.yaml" % (args.conf_dir, ))
    else:
        YAML_CONF = resource_filename("molteniron", "conf.yaml")

    with open(YAML_CONF, "r") as fobj:
        conf = yaml.load(fobj, Loader=yaml.SafeLoader)

        mi.setup_conf(conf)
        mi.setup_parser(parser)

        # Make a map of our arguments
        args_map = vars(args)
        # And call the function
        mi.call_function(args_map)

        ret = mi.get_response()

        json_ret = json.loads(ret)

        if output == "json":
            # Print the already JSON encoded reply sent from the server
            print(ret)
        elif output == "result":
            print(json_ret["result"])

        try:
            rc = mi.get_response_map()['status']
        except KeyError:
            print("Error: Server returned: %s" % (mi.get_response_map(),))
            rc = 444

        if rc == 200:
            exit(0)
        else:
            exit(rc)
