import { ChildProcess } from "child_process";
import colors from "./console-colors";
import kill from "kill-port";

let childProcess: ChildProcess | null = null;

/**
 * ## Kill Child Process Function
 * @param {string | number | (string | number)[]} [port]
 * @returns {Promise<boolean>}
 */
export default async function killChild(
    port?: string | number | (string | number)[]
): Promise<boolean> {
    if (!childProcess) return false;

    try {
        const childProcessPID = childProcess.pid;
        childProcess.kill();

        if (typeof port == "object" && port?.[0]) {
            for (let i = 0; i < port.length; i++) {
                const singlePort = port[i];
                await kill(Number(singlePort));
            }
        } else if (port) {
            await kill(Number(port));
        }

        return true;
    } catch (error: any) {
        console.log(
            `${colors.FgRed}Error:${colors.Reset} Child Process couldn't be killed! ${error.message}`
        );
        return false;
    }
}