// @ts-check

import { Server as HttpServer } from "http";
import path from "path";
import fs from "fs";
import { Server } from "socket.io";
import { parse } from "url";
import suSocketAuth from "../package-shared/functions/backend/suSocketAuth";
import parseCookies from "@/package-shared/utils/backend/parseCookies";

export default async function serverSocket(server: HttpServer) {
    const io = new Server(server);

    io.on("connection", async (socket) => {
        const req = socket.request;
        const parsedUrl = parse(req.url || "", true);
        const { pathname, query, href, search } = parsedUrl;
        const cookie = req.headers.cookie;
        const paradigm = req.headers["x-socket-paradigm"];

        const parsedCookies = parseCookies({ request: req });

        const suAdminUser = await suSocketAuth(req);

        const logPath = path.resolve(__dirname, "../log.log");

        if (!suAdminUser) return;

        switch (paradigm) {
            case "Console":
                try {
                    socket.emit("console", "Welcome");

                    process.stdin.on("data", (data) => {
                        console.log("STDOUT data =>", data.toString());
                    });

                    const originalConsoleLog = console.log;
                    console.log = function (...args) {
                        const logMessage = args
                            .map((arg) =>
                                typeof arg === "object"
                                    ? JSON.stringify(arg)
                                    : arg
                            )
                            .join(" ");
                        socket.emit("console", logMessage + "\n\r");

                        originalConsoleLog.apply(console, args);
                    };

                    socket.on("log", (log) => {
                        console.log(log);
                    });

                    socket.on("get-log", (log) => {
                        if (fs.existsSync(logPath)) {
                            socket.emit(
                                "console-log",
                                fs.readFileSync(logPath, "utf-8")
                            );
                        }
                    });

                    //////////////////////////////////////////
                    //////////////////////////////////////////
                    //////////////////////////////////////////

                    if (process.env.NEXT_PUBLIC_DSQL_LOCAL) {
                        const PAUSE = "\x13";
                        const CANCEL = "\x03";
                        const RESUME = "\x11";

                        // const ptyProcess = pty.spawn("bash", [], {
                        //     name: "xterm-color",
                        // });

                        // socket.on("shell", (message) => {
                        //     ptyProcess.write(message);
                        // });

                        // ptyProcess.onData((data) => {
                        //     socket.emit("shell", data);
                        // });

                        // socket.on("disconnect", () => {
                        //     ptyProcess.kill("SIGTERM");
                        // });
                    }

                    socket.on("clear-log", (message) => {
                        if (fs.existsSync(logPath))
                            fs.writeFileSync(logPath, "", "utf-8");
                    });
                } catch (error: any) {
                    console.log("Error in Console socket =>", error.message);
                }
                break;

            default:
                break;
        }
    });

    io.on("error", (err) => {
        console.log("Socket Server Error =>", err);
    });
}
