const express = require('express');
const app = express();
const http = require('http');
const { exit } = require('process');
const server = http.createServer(app);
const { Server } = require("socket.io");
const io = new Server(server);


let rooms = [];


app.get("/", (req, res) => {
    res.sendFile(__dirname + '/client/index.html');
});


app.get("/client/main.js", (req, res) => {
    res.sendFile(__dirname + '/client/main.js');
});


server.listen(21111, () => {
  console.log('listening on *:21111');
});


io.on('connection', (socket1) => {

    socket1.on('disconnect',(socket)=>{
        console.log(`[Server Side] disconnection : ${socket1.id}`)
        rooms.forEach(it =>{
            it.players = new Map(
                [...it.players]
                .filter(([k, v]) => k !== socket1.id )
            )
            roomChanged(it)
        })
    })

    socket1.on('testing', (socket) => {
        data = JSON.parse(socket);
        console.clear();
        console.log(`[Server Side] JSON : ${socket}`)
        console.log(`[Server Side] data : ${data.id}`)
        if(rooms.length === 0)
        {
            map = new Map();
            map.set(data.nom,0);
            rooms.push({
                id: data.id,
                players: map
            })
            roomChanged(rooms[0])
        }
        else
        {
            res = rooms.filter(e => e.id === data.id);
            if(res[0] != null )
            {
                console.log(res)
                if(res[0].players.get(data.nom) != null)
                {
                    console.log(`[Server Side] Error : le joueur ${data.nom} est dejà dans la room`);
                }
                else
                {
                    res[0].players.set(data.nom,0);
                    roomChanged(res[0])
                }
            }
            else{
                map = new Map();
                map.set(data.nom,0);
                rooms.push({
                    id: data.id,
                    players: map
                });
                roomChanged(rooms[rooms.length-1])
            }
        }
        displayAllRooms(rooms);
    })
})




function displayAllRooms(rooms)
{
    console.log(`[Server Side] number of rooms : ${rooms.length}`);
    console.log(`------------`);
    rooms.forEach(element => {
        console.log(`[Server Side] room : ${element.id}`);
        displayAllPlayers(element.players);
        console.log(`------------`);
    });
}

function displayAllPlayers(players)
{
    console.log("[Server Side]: Players :")
    players.forEach((element,key) => {
        console.log(`[Server Side]: ${key} -> ${element}`);
    });
}

function roomChanged(room)
{
    if(room.players.size === 0)
    {
        rooms = rooms.filter((it)=>{
            it !== room
        })
    }
    room.players.forEach((element,key) => {
        io.to(key).emit('players',JSON.stringify(Array.from(room.players.entries())))
    });
}

