import os
import psutil
import json

current_dir = os.path.dirname(os.path.abspath(__file__))
weshop_native_dir = os.path.join(current_dir, "..")
bin_dir = os.path.join(weshop_native_dir, "bin")
log_dir = os.path.join(weshop_native_dir, "logs")
pid_json = os.path.join(bin_dir,"pid.json")

class ConfigReader():
    def __init__(self) -> None:
        self.config_path = os.path.join(bin_dir, "config.json")
        with open(self.config_path, "r") as config_file:
            config_data = json.load(config_file)
        self.log_mode = config_data["log_mode"]
        self.config_data = config_data

    def write(self, key, value):
        with open(self.config_path, "r") as config_file:
            config_data = json.load(config_file)
        config_data[key] = value
        with open(self.config_path, "w") as config_file:
            json.dump(config_data, config_file)


configReader = ConfigReader()


def terminate_processes(pids):
    for pid in pids:
        try:
            parent_process = psutil.Process(pid)
            child_processes = parent_process.children(recursive=True)
            
            # Terminate child processes
            for child in child_processes:
                child.terminate()
                
            # Wait for child processes to terminate
            psutil.wait_procs(child_processes)

            # Terminate the parent process
            parent_process.terminate()
            
            print(f"Terminated process {pid} and its child processes.")
        
        except psutil.NoSuchProcess:
            print(f"No such process with PID {pid}.")


if __name__ == '__main__':
    def get_pid_list_by_port(port_list):
        pid_list = []
        pid_dict = {}
        for conn in psutil.net_connections():
            if conn.status == 'LISTEN' and conn.laddr.port in port_list:
                port_num = conn.laddr.port
                pid = conn.pid
                pid_list.append(conn.pid)
                if port_num not in pid_dict:
                    pid_dict[port_num] = []
                    
                pid_dict[port_num].append(pid)
                
        return pid_list, pid_dict
    
    boot_time = psutil.boot_time()
    if "boot_time" not in configReader.config_data or boot_time != configReader.config_data["boot_time"]:
        configReader.write(key="boot_time", value=boot_time)
    else:
        try:
            with open(os.path.join(bin_dir, "port_num.json"), "r") as pid_json_file:
                json_data = json.load(pid_json_file)
        except Exception as e:
                json_data = {"port_num": 30000}
        print(json_data)
        main_port_num = json_data["port_num"]
        port_num_list = [3000, 8080, 60020, 60030, 60040, 60041, 30001, 30002, 30003, 27017]
        port_num_list.append(main_port_num)
        pid_list, pid_dict = get_pid_list_by_port(port_num_list)
        print(pid_dict)
        terminate_processes(pid_list)
        try:
            with open(os.path.join(bin_dir, "pid.json"), "r") as process_pid_json:
                processes_pid_list = json.load(process_pid_json)
        except Exception as e:
            processes_pid_list = {"pid": []}
        terminate_processes(pid_list)
    with open(os.path.join(log_dir, "status.log"),'w') as status_log_file:
        print("weshop native status code: 2001", file=status_log_file, flush=True)
    with open(pid_json, "w", buffering=1) as file: 
        json.dump({"pid" : []}, file)
    

