socket = io();

const form = document.querySelector("#form");


socket.on("connect", () => {
  socket.on('roomID', (arguments) => {
    console.log(arguments)
    let balise = document.querySelector("h1")
    balise.innerHTML = `HyperSet - ${arguments}`
  })
    socket.on("players",(socket) => {
        data = new Map(JSON.parse(socket));
        console.log(data);
        const player = document.querySelector("#players")
        player.innerHTML=''
        data.forEach((it,key) => {
            let p = document.createElement("p");
            p.innerHTML = `joueur : ${key}   points : ${it}`;
            player.appendChild(p);
        })
    })
})




form.addEventListener('submit',function(e){
    e.preventDefault();
    const value = form.querySelector("input[name=pseudo]").value;
    let room = form.querySelector("input[name=id]").value;
    console.log(room)
    if (room === "") {
      console.log("EMPTY VALUE")
      room = makeid(5)
    }

    if(value)
    {
        perso = {
            id: room,
            joueur: value,
            nom: socket.id,
        }
        data = JSON.stringify(perso);
        console.log(`[Client Side] inputValue : ${data}`);
        socket.emit('createRoom',data);
    }
})


function makeid(length) {
    let result = '';
    const characters = 'abcdefghijklmnopqrstuvwxyz0123456789';
    const charactersLength = characters.length;
    let counter = 0;
    while (counter < length) {
      result += characters.charAt(Math.floor(Math.random() * charactersLength));
      counter += 1;
    }
    return result;
}
