import argparse
import sys

from .connect import connect
from .ping import ping
from .pull import pull
from .push import push
from .status import status


def run(args=None, **extra_args):
    parser = _cmd_parser()
    if len(sys.argv) < 2:
        parser.print_usage()
        sys.exit(1)

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


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

    connect_parser = subparsers.add_parser(
        'connect', help="Create a node in the current working directory."
    )
    connect_parser.add_argument(
        'hub_url', type=str, help="the url of the hub you want to connect to"
    )
    connect_parser.set_defaults(cmd=connect)

    ping_parser = subparsers.add_parser(
        'ping', help="Check if the hub connected to this node is up and running."
    )
    ping_parser.set_defaults(cmd=ping)

    pull_parser = subparsers.add_parser(
        'pull', help="Sync this node's collection and pull newer revisions from the hub."
    )
    pull_parser.set_defaults(cmd=pull)

    status_parser = subparsers.add_parser(
        'status', help="Check local revision, local collection changes and remote revision."
    )
    status_parser.set_defaults(cmd=status)

    push_parser = subparsers.add_parser(
        'push', help="Upload local changes to the hub."
    )
    push_parser.set_defaults(cmd=push)
    return parser
