let source_url = ""
let partyRef = document.getElementById("partyRef")
let seatRef = document.querySelector(".seat")
let hemicycle = document.getElementsByClassName("hemicycle")[0]
let row = 5

let btn = document.getElementById("info-btn")
let info = document.getElementById("info")

fetch("https://hub.xpub.nl/soupboat/the-parliament/")
    .then((response) => response.json()) 
    .then((data) => {
        source_url = data.base_url;
        populateSeats(data.parliament)
    }); 

function populateSeats(parliament) {
    for (const group of Object.keys(parliament)){  //gets the parent's keys
        let party = partyRef.cloneNode(true);
        let partyName = party.querySelector("h4")
        party.id = group;
        
        partyName.innerHTML = group;
        for (representative of parliament[group]){
            let seat = seatRef.cloneNode(true);
            seat.querySelector(".label").innerHTML = representative.who;
            seat.id = representative.who;
            let filename = source_url + group + '/' + representative.filename;
            let audio = new Audio(filename)
            audio.addEventListener("canplaythrough", (e) => {
                console.log(filename);
                let mic = seat.querySelector(".mic");
                mic.innerHTML = "Talk";
                mic.addEventListener("click", () => {
                    console.log(filename);
                    if (audio.paused) {
                        audio.play();
                        mic.innerHTML="Pause";
                        mic.style.color ="white";
                        mic.style.background = "red"
                    } else {
                        audio.pause();
                        mic.innerHTML="Talk"
                        
                    }
                });
                audio.addEventListener("ended", () => {
                    audio.pause();
                    audio.currentTime = 0;
                    mic.style.background = "white"
                    mic.style.color ="red";
                });
            });
            party.appendChild(seat);
        }
        
        hemicycle.appendChild(party);

    }
}

// info
btn.addEventListener("click", showInfo)


function showInfo(){
    
    if (info.style.display === "none"){
        btn.innerHTML = "X";
        console.log("click");
        info.style.display = "block";
    } else {
        btn.innerHTML = "?";
        info.style.display = "none";
    }
}

/*
 TODO
 - upload svg
 - loop through the elements to associate seat to each of them
 - create label 
 - rotation? 
*/