const parts = window.location.pathname.split('/').filter(Boolean);
const sessionId = parts[0] ?? null;
const username = parts[1] ?? null;
//console.log(sessionId, username)


const hello_username_div = document.getElementById('hello_username')
hello_username_div.textContent = `Hallo ${username}👋`

//liste an user zurückgeben
setInterval(show_user, 2000);
async function show_user() {
    //console.log(sessionId)
    const res = await fetch(`/api/user/${sessionId}`);
    const users = await res.json();
    const allUsers = users.map(u => u.ready);
        if(allUsers.every(v => v === 1))  {
        window.location.href = window.location.href = `/${sessionId}/${username}/game`
    }

    const user_div = document.getElementById('users');
    
    //todo ready status hinzufügen, eventuell WS nutzen
    for (let i = 0; i < users.length; i++) {
        const userObj = users[i];
        if (!document.getElementById(userObj.user)) {
            const new_div = document.createElement('div');
            new_div.className = 'user';
            new_div.id = userObj.user;
            new_div.textContent = userObj.user;
            user_div.appendChild(new_div);
        }
    }
}
//ready status updaten
async function ready() {
    const data = {
        user: username,
        ready: 1,
    }
    const  res = await fetch(`/api/ready/${sessionId}`, {
        method: 'PUT',
        headers: {
            'Content-Type': 'application/json',
        },
        body: JSON.stringify(data)
    });
    
    const resObj = await res.json();
    console.log(resObj.ready)

    //statusänderung des buttons abhänging von der server response
    const readyButton = document.getElementById('readyButton');
    if (resObj.ready == true) {
        readyButton.classList.toggle('active');
        readyButton.textContent = "Bereit!"
    } else {
        readyButton.classList.toggle('active');
        readyButton.textContent = "Nicht Bereit!"
    }
    
}