#!/usr/bin/env python3
import argparse
import json
import os
import os.path as pt
import shutil
import subprocess

name = "voxl-mini-tof-server"
# Location of single-file configuration
conf_file = pt.abspath(f"/etc/modalai/{name}.conf")
# Location of multi-file configuration
conf_dir = pt.abspath(f"/etc/modalai/{name}.conf.d/")
# Location of available default configurations
default_confs_dir = pt.abspath(f"/etc/default/modalai/{name}")
#default_confs_dir = pt.abspath(pt.join(pt.dirname(__file__), f"../default/{name}"))

service_file = "{}.service".format(name)

WIZARD_HEADER = \
"""
This wizard will configure your VL53 rangefinders.
"""

all_options = {
    "enable": "Enable and start the current configuration",
    "disable": "Disable and stop the server",
    "create": "Create a new configuration (deletes any existing configurations)",
    "append": "Add a new configuration onto the existing configuration",
    "autosku": "Autodetect the rangefinder configuration based on the SKU string (deletes any existing configurations)",
    "delete": "Remove an existing configuration from the list",
    "delete_all": "Remove all existing configurations",
    "exit": "Quit this wizard",
}

SKU_CONFIGS = {
    "MRB-D0014": ["Downward On M0173"]
}


def enable_service():
    """
    Uses systemd to enable and (re)starts the voxl-mini-tof-service service
    """
    subprocess.run(["systemctl","enable",service_file])
    subprocess.run(["systemctl","restart",service_file])


def disable_service():
    """
    Uses systemd to disable and stop the voxl-mini-tof-service service
    """
    subprocess.run(["systemctl","stop",service_file])
    subprocess.run(["systemctl","kill", "--signal=SIGKILL", service_file])
    subprocess.run(["systemctl","disable",service_file])


def get_config_name(file: str):
    """
    file -- The file to get the config's name from
    """
    with open(file, "r") as fp:
        return json.load(fp)["conf_name"]
    
def get_bus(file: str):
    with open(file, "r") as fp:
        return int(json.load(fp)["i2c_bus"])


def get_all_conf_dir(dirname: str):
    return [pt.join(dirname, x) for x in os.listdir(dirname) if pt.splitext(x)]


def get_current_config():
    if(pt.exists(conf_file)):
        return [get_config_name(conf_file)]
    elif(pt.exists(conf_dir)):
        return [get_config_name(cf) for cf in get_all_conf_dir(conf_dir)]
    else:
        return None


def delete_old_confs():
    if(pt.exists(conf_file)):
        os.remove(conf_file)
    if(pt.exists(conf_dir)):
        shutil.rmtree(conf_dir)

def switch_one_to_many():
    if(pt.exists(conf_file)):
        if(pt.exists(conf_dir)):
            shutil.rmtree(conf_dir)
        os.makedirs(conf_dir, exist_ok=True)
        shutil.move(conf_file, conf_dir)
    else:
        os.makedirs(conf_dir, exist_ok=True)


def get_defaults():
    return get_all_conf_dir(default_confs_dir)


def get_available_options():
    options = ["exit", "disable", "create", "autosku"]
    current_conf = get_current_config()
    if current_conf is not None and len(current_conf) > 0:
        options.extend(["append", "delete", "delete_all", "enable"])
    return options

def get_conf_from_sku():
    SKU_FILE = "/data/modalai/sku.txt"
    sku_list = []
    with open(SKU_FILE, "r") as f:
        sku_str = f.read()
        for k, v in SKU_CONFIGS.items():
            if k in sku_str:
                print(f"Adding configuration {v} from SKU string {k}")
                sku_list.extend(v)
    return sku_list
        


def wizard_options(options: list, options_dict: dict):
    i = 1
    opt_l = []
    for opt in options_dict.keys():
        if opt in options:
            opt_l.append(opt)
            print(f" {i}. {options_dict[opt]}")
            i += 1

    sel = input("> ")
    if int(sel) in range(1, i):
        return opt_l[int(sel) - 1]
    elif sel in options:
        return sel
    

def get_file_from_defaults():
    opts = {x: get_config_name(x) for x in get_defaults()}
    opts["cancel"] = "Cancel"
    print("Which configuration would you like to use?")
    return wizard_options(opts.keys(), opts)


def append_conf(filename):
    shutil.copy(filename, conf_dir)

def run_interactive_wizard():
    """
    This is the interactive wizard the user will see if they run this
    script without args.
    """
    print(WIZARD_HEADER)
    current_conf = get_current_config()

    if current_conf is not None and len(current_conf) > 0:
        print(f"Your current configuration:", end=" ")
        print(*current_conf, sep=", ")
    else:
        print("No valid configuration is currently loaded!\n")
    print("\n==================================================")

    first = True
    opt = None
    while not opt == "exit":
        print("What do you want to do?")

        current_conf = get_current_config()
        if current_conf is not None and len(current_conf) > 0 and not first:
            print(f"Your current configuration:", end=" ")
            print(*current_conf, sep=", ")
        first = False

        # Print available options
        opt = wizard_options(get_available_options(), all_options)

        if opt == "enable":
            enable_service()
        if opt == "disable":
            disable_service()
        if opt == "append":
            switch_one_to_many()
            f = get_file_from_defaults()
            if f != "cancel":
                shutil.copy(f, conf_dir)
                print("Added new configuration")
            else:
                print("Canceled!")
        if opt == "create":
            delete_old_confs()
            f = get_file_from_defaults()
            if f != "cancel":
                shutil.copy(f, conf_file)
                print("Added new configuration")
            else:
                print("Canceled!")
        if opt == "delete":
            if len(current_conf) > 1:
                opts = {x: get_config_name(x) for x in get_all_conf_dir(conf_dir)}
                opts["cancel"] = "Cancel"
                print("Which configuration would you like to remove?")
                o = wizard_options(opts.keys(), opts)
                if not o == "cancel":
                    os.remove(o)
                    print("Deleted configuration")
                else:
                    print("Canceled!")
            else:
                delete_old_confs()
                print("Deleted configuration")
        if opt == "delete_all":
            delete_old_confs()
            print("Deleted old configuration")
        if opt == "autosku":
            sku = get_conf_from_sku()
            if sku is not None and len(sku) > 0:
                delete_old_confs()
                opts = {x: get_config_name(x) for x in get_defaults()}
                for k, v in opts.items():
                    if v in sku:
                        if(len(sku) > 1):
                            shutil.copy(k, conf_dir)
                        else:
                            shutil.copy(k, conf_file)
                print("Added new configuration")
            else:
                print("Couldn't find the configuration for your SKU")

            


available_defaults = {get_config_name(x): x for x in get_defaults()}
    
if __name__ == "__main__":
    available_options = available_defaults.keys()
    parser = argparse.ArgumentParser(
        prog="voxl-configure-mini-tofs",
        description='Configures VL53 series ToF sensors for use with voxl-mini-tof-server',
        epilog='Start the interactive wizard with -i if you are not sure what to do.'
    )
    parser.add_argument(
        '-l',
        '--list',
        help="Lists all available configurations",
        action='store_true'
    )
    parser.add_argument(
        '-s',
        '--set',
        help="Sets the configuration(s) with the configuration name(s) following this flag",
        nargs='+',
        choices=available_options
    )
    parser.add_argument(
        '-i',
        '--interactive',
        help="Start the interactive wizard",
        action='store_true'
    )

    args = vars(parser.parse_args())

    if args["list"] is not None and args["list"] == True:
        print("The available configuration options are the following:")
        for i, k in enumerate(available_defaults):
            print(f"{i}. {k}:\t{available_defaults[k]}")
    elif args["set"] is not None and len(args['set']) > 1:
        delete_old_confs()
        [append_conf(available_defaults[x]) for x in args["set"]]
    elif args["set"] is not None and len(args['set']) == 1:
        delete_old_confs()
        shutil.copy(available_defaults[args["set"][0]], conf_file)
    elif args["interactive"] is not None and args["interactive"] == True:
        run_interactive_wizard()
    else:
        parser.print_help()

    #run_interactive_wizard()