#!/usr/bin/env python3
import os
import sys
import necxxt.commands

import necxxt

__executable__ = os.path.basename(__file__)


class ArgumentsRunner():
    def __init__(self):
        self._cmds = {}

    def help(self):
        print()
        print("Usage: {} <command>".format(__executable__))
        print()
        print("where <command> is one of:")

        for cmd in sorted(list(self._cmds.keys()) + ["help"]):
            print("    {}".format(cmd))

        print()
        print("{} <command> -h  quick help on <command>".format(__executable__))
        print()
        print("{}@{} {}".format(__executable__, necxxt.__version__, __file__))

    def add_command(self, name, command):
        self._cmds[name] = command

    def run(self, args=None):
        if not args:
            args = sys.argv[1:]

        cmd = None
        if len(args) > 0:
            cmd = args.pop(0)

        if not cmd or cmd == "help":
            self.help()
            exit(0)
        elif not cmd in self._cmds.keys():
            self.help()
            exit(1)

        if len(args) > 0 and args[0] == "-h":
            self._cmds[cmd].help()
        else:
            _args = []
            _kwargs = {}

            i = 0
            while i < len(args):
                arg = args[i]
                if arg.startswith("--") and (i + 1) < len(args):
                    _kwargs[arg[2:]] = args[i + 1]
                    i += 1
                elif arg.startswith("-") and (i + 1) < len(args):
                    _kwargs[arg[1:]] = args[i + 1]
                    i += 1
                else:
                    _args.append(arg)

                i += 1

            self._cmds[cmd].run(*_args, **_kwargs)


if __name__ == "__main__":
    runner = ArgumentsRunner()
    runner.add_command("build", necxxt.commands.BuildCommand())
    runner.add_command(
        "check-coverage", necxxt.commands.CheckCoverageCommand())
    runner.add_command("init", necxxt.commands.InitCommand())
    runner.add_command("install", necxxt.commands.InstallCommand())
    runner.add_command("run", necxxt.commands.RunCommand())

    runner.run()
