import { ServerWebSocket } from "bun";
import { WebSocketData } from "../types";
import killAllTtydPorts from "./(utils)/kill-all-ttyd-ports";

type Param = {
    ws: ServerWebSocket<WebSocketData>;
};

export default async function socketClose({ ws }: Param) {
    const user = ws.data.user;
    console.log(`Web Socket Closed by ${user.first_name}`);

    const existing_connected_user_data =
        global.WEBSOCKET_CONNECTED_USERS_DATA.find((u) => u.user.id == user.id);

    if (existing_connected_user_data) {
        for (
            let i = 0;
            i < existing_connected_user_data.child_processes.length;
            i++
        ) {
            const child_process =
                existing_connected_user_data.child_processes[i];
            child_process.kill();
        }

        existing_connected_user_data.child_processes = [];
    }

    killAllTtydPorts({ user });
}
