#!/usr/bin/python3
# pylint: disable=invalid-name  # https://github.com/PyCQA/pylint/issues/516
import json
import logging

import mini_buildd.api
import mini_buildd.client
import mini_buildd.cli

LOG = logging.getLogger("mini_buildd")

#: Needed for man page hack in setup.py
DESCRIPTION = "Run API calls and monitor events"


class CLI(mini_buildd.cli.CLI):
    def __init__(self):
        super().__init__("mini-buildd-api", DESCRIPTION,
                         "Note: Uses 'python-keyring' to persist passwords (see '~/.local/share/python_keyring/')")

        self.parser.add_argument("-J", "--json", action="store_true",
                                 help="use parsable json output")
        self.parser.add_argument("--auto-confirm", action="store_true",
                                 help="force-bypass extra confirmation (for confirmable commands)")
        self.parser.add_argument("--auto-save-passwords", action="store_true",
                                 help="don't ask before saving passwords (via python-keyring)")

        # Unfortunately, we cannot group the commands (yet), see http://bugs.python.org/issue14037, https://bugs.python.org/issue9341
        self.subparsers = self.parser.add_subparsers(title="API commands (run 'mini-buildd-api <cmd> --help' for full single command help)",
                                                     required=True,
                                                     metavar="<cmd> [options]")

        for cmd, cmd_cls in mini_buildd.api.COMMANDS.items():
            if not cmd_cls.isgroup():
                cmd_parser = self._add_subparser(self.subparsers, cmd, cmd_cls.doc() + "\n.")
                self._add_endpoint(cmd_parser)
                for argument in cmd_cls.ARGUMENTS:
                    cmd_parser.add_argument(*argument.id_list, **argument.argparse_kvsargs)
                cmd_parser.set_defaults(command=cmd_cls)

    def runcli(self):
        result = mini_buildd.client.Client(self.args.endpoint,
                                           auto_confirm=self.args.auto_confirm,
                                           auto_save_passwords=self.args.auto_save_passwords).api(self.args.command.name(), self.args.command.api_args(self.args.__dict__))
        print(json.dumps(result) if self.args.json else mini_buildd.api.Command.get_plain(result))


CLI().run()
