import { spawn } from "child_process";
import { eq } from "drizzle-orm";
import { tryCatch } from "../../../../globalUtils/tryCatch.js";
import { db } from "../../../../../database/dbclient.js";
import { createLog } from "../../../logger/logger.js";
import { serverData } from "../../../../../database/schema/serverData.js";
import os from "os";

export const serviceControl = async (
    plantToken: string,
    processType: string,
    remote: string | null
) => {
    const { data: serverInfo, error: serverError } = await tryCatch(
        db
            .select()
            .from(serverData)
            .where(eq(serverData.plantToken, plantToken))
    );

    if (serverError) {
        return createLog(
            "error",
            "lst",
            "serverUpdater",
            `Error getting the server settings`
        );
    }

    let scriptPath = `${serverInfo[0].serverLoc}\\dist\\server\\scripts\\services.ps1`;
    if (os.hostname() != serverInfo[0].serverDNS) {
        scriptPath = `${process.env.DEVFOLDER}\\dist\\server\\scripts\\services.ps1`;
    }

    console.log(serverInfo[0].serverDNS);
    const username = process.env.ADMUSER as string;
    const password = process.env.ADMPASSWORD as string;

    console.log(username, password);

    const args = [
        "-NoProfile",
        "-ExecutionPolicy",
        "Bypass",
        "-File",
        scriptPath,
        "-serviceName",
        "LSTV2",
        "-option",
        processType,
        "-appPath",
        serverInfo[0].serverLoc as string,
        "-remote",
        remote ?? "",
        "-server",
        serverInfo[0].serverDNS as string,
        "-username",
        username,
        "-admpass",
        password,
    ];
    const scriptProcess = spawn("powershell", args);

    // Collect stdout data
    scriptProcess.stdout.on("data", (data) => {
        const output = data.toString().trim();
        createLog("info", "lst", "serverUpdater", `${output}`);
        //onData(output);
    });

    // Collect stderr data
    scriptProcess.stderr.on("data", (data) => {
        const output = data.toString().trim();
        createLog("info", "lst", "serverUpdater", `${output}`);
        //onData(output);
    });

    // Handle process close
    scriptProcess.on("close", async (code) => {
        if (code === 0) {
            // if (count >= servers) {
            //     //onClose(`Server completed with code: ${code}`);
            // }
            createLog("info", "lst", "serverUpdater", `Finished setting perms`);

            //update the last build.
        } else {
            const errorMessage = `Process exited with code ${code}`;

            // if (count >= servers) {
            //     //onClose(code);
            // }
        }
    });

    // Handle errors with the process itself
    scriptProcess.on("error", (error) => {
        //onError(err.message);
        createLog("error", "lst", "serverUpdater", `${error}`);
    });
};
