import sys
import subprocess
import argparse
import logging
import plugin_sdk
from plugin_sdk import validator, plugin_build, plugin_simulator, demo_app, plugin_upload
import os
import signal

logging.basicConfig(stream=sys.stderr, format="%(message)s", level=logging.INFO)
log = logging.getLogger(__name__)

def keyboardInterruptHandler(signal, frame):
    exit(0)

def _parse_args(cmd_args):
    parser = argparse.ArgumentParser(description="Use one of the following argument to invoke certain command. See 'plugin_sdk <command> --help' to read about a specific command.")
    subparsers = parser.add_subparsers(dest="action")
    subparsers.add_parser(name="verify_plugin", help='checks plugin.json')
    subparsers.add_parser(name="build_plugin", help='builds plugin')
    subparsers.add_parser('upload_plugin', help="uploads plugin zip")
    subparsers.add_parser('simulate_plugin', help="starts plugin simulator")
    subparsers.add_parser('start_demo_app', help="starts demo application")
    subparsers.add_parser('start_demo_app_auth', help="starts demo_auth application")

    __version__ = plugin_sdk.sdk_version.get_version()

    parser.add_argument(
        "--version",
        action="version",
        help="show program's version and exit",
        version=("{name} {version}".format(name=__package__, version=__version__)),
    )
    args = parser.parse_args(cmd_args)
    return args


def main():
    if len(sys.argv) == 1:
         sys.argv.append("--help")
    options = _parse_args([sys.argv[1]])
    signal.signal(signal.SIGINT, keyboardInterruptHandler)
    python_ = sys.executable
    to_run = ""
    if options.action == "verify_plugin":
        to_run = "plugin_sdk.validator"
    if options.action == "build_plugin":
        to_run = "plugin_sdk.plugin_build"
    if options.action == "upload_plugin":
        to_run = "plugin_sdk.plugin_upload"
    if options.action == "simulate_plugin":
        to_run = "plugin_sdk.plugin_simulator"
    if options.action == "start_demo_app":
        to_run = "plugin_sdk.demo_app"
    if options.action == "start_demo_app_auth":
        to_run = "plugin_sdk.demo_app_auth"

    subprocess.run([python_, "-m", to_run, *sys.argv[2:]])


if __name__ == "__main__":
    main()