#!/usr/bin/env python3

import sys
import sqlite3
from htc_debug_tool.htc_get_modules import getModuleList
from htc_debug_tool.htc_get_modules import sendMessage

def sendDebugMessage(ipAddress, port, module, debugLevel):
        msg = f'{{"MessageType":"SYS_DEBUG_STATE", "TARGET_MODULE":"{module}", "DEBUG_LEVEL":"{debugLevel}", "DEBUG_OUTPUT":"console"}}'
        sendMessage(ipAddress, port, msg)

def main():
    """ a simple CLI program to enable local debug (intended to run on the target)
    """
    def notify_modules_found(target_ip, module_list):
        print(f"\nModules found for IP {target_ip}:")
        print("===============================\n")
        index = 1
        modules_selection = {}
        for module_info in module_list:
            print(f"{index}.\t{module_info[0]}")
            modules_selection[index] = module_info
            index = index + 1
        print("\n")
        print("Index of module to debug?")
        try:
            selected_index = int(input())
        except ValueError:
            print("Invalid value")
            return

        if selected_index in modules_selection:
            module_info = modules_selection[selected_index]
            print(f"\nSelect debug level for {module_info[0]}:")
            print("==========================================\n")
            index = 1
            debug_values=['DEBUG_NONE', 'DEBUG_FATAL','DEBUG_ERROR','DEBUG_WARN', 'DEBUG_NOTICE', 'DEBUG_INFO', 'DEBUG_TRACE']
            debug_value_selection = {}
            for debug_value in debug_values:
                print(f"{index}.\t{debug_value}")
                debug_value_selection[index] = debug_value
                index = index + 1
            print("\n")
            try:
                value_index = int(input())
            except ValueError:
                print("Invalid value")
                return

            if value_index in debug_value_selection:
                debug_value = debug_value_selection[value_index]
                sendDebugMessage(target_ip, module_info[1], module_info[0], debug_value)
                print(f"\nDebug set to {debug_value} for module {module_info[0]} port {module_info[1]} on IP {target_ip}")

                response = input("\nPersist debug after reboot? y/n: ")
                if response.lower() == 'y':
                    con = sqlite3.connect("/usr/local/htc/database/HTC.db")
                    con.execute(f"UPDATE parameters SET value ='{debug_value}' WHERE tag='DEBUG_LEVEL' and module_id = (SELECT id FROM modules WHERE symbol='{module_info[0]}')")
                    # Check if we need to update or insert the debug output parameter
                    res = con.execute(f"SELECT * FROM parameters WHERE tag='DEBUG_STD_TYPE' and module_id = (SELECT id FROM modules WHERE symbol='{module_info[0]}')")
                    if len(res.fetchall()) > 0:
                        con.execute(f"UPDATE parameters SET value ='stdout' WHERE tag='DEBUG_STD_TYPE' and module_id = (SELECT id FROM modules WHERE symbol='{module_info[0]}')")
                    else:
                        con.execute(f"INSERT INTO parameters (module_id,tag,symbol,value,paramtype_id) SELECT modules.id,'DEBUG_STD_TYPE','','stdout',1 FROM modules WHERE symbol='{module_info[0]}'")
                    con.commit()
                    print("\nDatabase updated")
            else:
                print("Invalid index")
        else:
            print("Invalid index")

    # Argument check
    if len(sys.argv) > 1 and sys.argv[1] == '-h':
        sys.stderr.write('usage:' + sys.argv[0] + ' [ip_address]\n')
        sys.exit(2)

    target_ip_address = "127.0.0.1"
    if len(sys.argv) > 1:
        target_ip_address = sys.argv[1]

    # Do the work
    getModuleList(target_ip_address, notify_modules_found)

if __name__ == "__main__":
    main()
