import http from "http";
import sockerIO from "socket.io";

export default class SocketServer {

    public port: number;
    public io: SocketIO.Server;
    public modelClientsMap: Map<string, string[]>;

    constructor(port) {
        this.port = port;
        this.modelClientsMap = new Map();
    }

    public start(): void {
        // Create server
        const server = http.createServer();
        this.io = sockerIO(server);

        this.io.on("connection", (client) => {

            client.on("listenModel", (data) => {
                if (data.modelId) {
                    if (this.modelClientsMap.has(data.modelId)) {
                        const clientList = this.modelClientsMap.get(data.modelId);
                        clientList.push(client.id);
                    } else {

                        this.modelClientsMap.set(data.modelId, [client.id]);
                    }
                }
            });

            client.on("disconnect", () => {
               for (const clientList of Array.from(this.modelClientsMap.values())) {
                    if (clientList.includes(client.id)) {
                        clientList.splice( clientList.indexOf(client.id), 1 );
                    }
               }
            });
         });

        server.listen(this.port, () => {
            console.log("socket server is listening on port", this.port);
        });
    }

    public notifyCrossEntropy(crossEntropy: number, modelId: string): void {
        console.log('notify cross entropy:',crossEntropy, modelId);
        if (this.modelClientsMap.has(modelId) && crossEntropy != undefined && crossEntropy != null) {
            const clientList = this.modelClientsMap.get(modelId);

            clientList.forEach((clientId) => {
                this.io.to(clientId).emit("crossEntropy", JSON.stringify({crossEntropy}));
            });
        }
    }

}
