import { DefaultEventsMap, Server } from "socket.io";

let io: Server<DefaultEventsMap, DefaultEventsMap, DefaultEventsMap, any>;

export const initWebsocket = (server: any) => {
    io = new Server(server, {
        cors: {
            origin: "*",
        },
    });
    io.on("connection", (socket) => {
        console.log(`New client connected: ${socket.id}`);

        socket.on("join", (login: string) => {
            if (login && typeof login === "string") {
                socket.join(`user:${login}`);
            }
        });

        socket.on("message", (message) => {
            io.emit("message", message);
        });

        socket.on("disconnect", () => {
            console.log(`Client disconnected: ${socket.id}`);
        });
    });
    return io;
}

export const getWebsocket = () => io;

/** Pošle event konkrétnímu přihlášenému uživateli (pokud je připojen). */
export const emitToUser = (login: string, event: string, data: unknown) => {
    if (!io) return;
    io.to(`user:${login}`).emit(event, data);
}