import argparse

import os
import sys

from .init import init
from .run import run_flask


def main(args=None):
    parser = _cmd_parser()
    if len(sys.argv) < 2:
        parser.print_usage()
        sys.exit(1)

    try:
        args = vars(parser.parse_args(args=args))
        cmd = args.pop("cmd")
        cmd(**args)
    except KeyboardInterrupt:
        print("\naborted")


def _cmd_parser():
    parser = argparse.ArgumentParser(prog="klon-hub")
    subparsers = parser.add_subparsers()
    subparsers.required = True

    init_parser = subparsers.add_parser('init', help="Create a hub in the given directory")
    init_parser.add_argument(
        'db_path', nargs='?', default=os.getcwd(),
        help="The hub's directory. Omit to use current working directory."
    )
    init_parser.set_defaults(cmd=init)

    run_parser = subparsers.add_parser('run', help="Run a hub in the given directory")
    run_parser.add_argument(
        'db_path', nargs='?', default=os.getcwd(),
        help="The hub's directory. Omit to use current working directory."
    )
    run_parser.add_argument('--debug', action='store_true', help=argparse.SUPPRESS)
    run_parser.add_argument('--testing', action='store_true', help=argparse.SUPPRESS)
    run_parser.set_defaults(cmd=run_flask)
    return parser
