const makeClusterButton = document.getElementById("makeCluster")
let numClusters

let openSlide = "spotlightContainer"

let clusters = {}
let occupiedLamps = Array()
let chosenShelves = Array()

let chosenCluster = -1

let clusterName = "Inte vald"

function getEByID(id) {
    return document.getElementById(id)
}

function shelfClick(id) {
    const clickedShelf = getEByID("b" + id.toString())
    console.log(chosenCluster >= 0)
    if (chosenCluster >= 0) {
        unselectAll()
    }
    chosenCluster = -1

    if (!occupiedLamps.includes(id)) { //If not id in clusters
        if (chosenShelves.includes(id)) { //If id in chosenShelves
            chosenShelves = chosenShelves.filter(e => {
                return e !== id;
            })
            clickedShelf.classList.remove("selected")
            clickedShelf.innerText = ""
        } else { //Else (if id not in chosenShelves
            chosenShelves.push(id)
            clickedShelf.classList.add("selected")
        }
    }

    chosenShelves.forEach((id, num) => {
        getEByID("b" + id.toString()).innerText = (num + 1).toString()
    })


    if (chosenShelves.length > 0) {
        makeClusterButton.classList.remove("hidden")
    } else {
        makeClusterButton.classList.add("hidden")
    }
}

function createCluster() {
    const shelves = chosenShelves
    const numLights = chosenShelves.length
    const sendDict = {
        ["numLights"]: numLights,
        ["lights"]: shelves
    }
    console.log(JSON.stringify(sendDict))
    sendWebRequest("http://192.168.1.170/api/create_cluster", JSON.stringify(sendDict), "POST")
}


window.onkeydown = function (event) {
    if (event.key === "Escape") {
        unselectAll()
    }
}

function deleteCluster() {
    if (chosenCluster >= 0) {
        const sendDict = {
            ["cluster"]: chosenCluster,
        }
        chosenCluster = -1
        sendWebRequest("http://192.168.1.170/api/delete_cluster", JSON.stringify(sendDict), "POST")
    }
}

function changeAnimation(animId) {
    const sendDict = {
        ["targetCluster"]: chosenCluster,
        ["animation"]: animId
    }
    console.log(JSON.stringify(sendDict))
    sendWebRequest("http://192.168.1.170/api/change_animation", JSON.stringify(sendDict), "POST")
}

function changeVar(value, setting) {
    let sendValue = 0

    if (value.substring(0,2) === "0x") {
        sendValue = parseInt(value, 16);
    } else if (value.substring(0,2) === "0c") {
        const r = parseInt(value.substring(2, 5));
        const g = parseInt(value.substring(5, 8));
        const b = parseInt(value.substring(8, 11));
        const w = parseInt(value.substring(11, 15));
        //console.log(r, g, b, w)
        sendValue = ((r << 24) + (g << 16) + (b << 8) + w) >>>0
        //console.log(sendValue)
        //console.log((sendValue >>> 0).toString(2))
    } else if (value.substring(0,2) === "0t") {
        const lowAndHigh = value.split(":")
        const lowTime = parseInt(lowAndHigh[0]);
        const highTime = parseInt(lowAndHigh[1]);
        sendValue = (lowTime << 16) + highTime >>>0
    } else {
        sendValue = Number(value)
    }


    if (!isNaN(sendValue) && sendValue >= 0) {
        const sendDict = {
            ["targetCluster"]: chosenCluster,
            ["newValue"]: sendValue,
            ["setting"]: setting
        }
        console.log(JSON.stringify(sendDict))
        sendWebRequest("http://192.168.1.170/api/change_setting", JSON.stringify(sendDict), "POST")
    }
}

function sendWebRequest(url, data, method) {
    /*const Http = new XMLHttpRequest()
    Http.open(method, url)
    Http.setRequestHeader("data", data)
    Http.send()

    Http.onreadystatechange = (e) => {
        console.log(Http.responseText)
    }*/

    fetch(url, {
        method: method,
        headers: new Headers({'data': data}),
        //mode: 'no-cors'
    })
        .then(res => {
            console.log(res)
            updateConfig()
        })
}

function chooseCluster(id) {
    if (id < 0) {
        return
    }

    unselectAll()
    getEByID("c" + id.toString()).classList.add("selected")
    chosenCluster = id
    let lampId = 0
    for (let lamp of clusters[id].lights) {
        console.log(lamp)
        getEByID("b" + lamp.toString()).classList.add("selected")
        getEByID("b" + lamp.toString()).innerText = (lampId + 1).toString()
        lampId += 1
    }

    getEByID("a" + clusters[id]["animation"].toString()).classList.add("selected")
    chosenShelves = clusters[id].lights
}

function unselectAll() {
    chosenCluster = -1
    chosenShelves.forEach(id => {
        getEByID("b" + id.toString()).innerText = ""
        getEByID("b" + id.toString()).classList.remove("selected")
    })
    const clustHTML = getEByID("clusters").children
    for (let b of clustHTML) {
        b.classList.remove("selected")
    }
    const animHTML = getEByID("spotlightAnimations").children
    for (let b of animHTML) {
        b.classList.remove("selected")
    }
    chosenShelves = Array()
    makeClusterButton.classList.add("hidden")
}

function updateConfig() {
    const preSelectCluster = chosenCluster
    unselectAll()
    fetch("http://192.168.1.170/api/get_config")
        .then(response => response.json())
        .then(data => {
            console.log(data)
            numClusters = data["numClusters"]
            clusters = data["clusters"]

            while (getEByID("clusters").firstChild) {
                getEByID("clusters").lastChild.remove()
            }

            occupiedLamps = Array()
            let id = -1
            for (const cluster of data.clusters) {
                id++
                for (let lamp of cluster.lights) {
                    occupiedLamps.push(lamp)
                }

                let clusterButton = document.createElement("button")
                clusterButton.innerText = (id + 1).toString()
                clusterButton.id = "c" + id.toString()
                clusterButton.setAttribute("onclick", "chooseCluster(" + id.toString() + ")")
                getEByID("clusters").appendChild(clusterButton)
            }

            chosenCluster = preSelectCluster
            chooseCluster(chosenCluster)
        })

}



function topBarClick(id) {
    if (id !== openSlide) {
        document.getElementById(id).classList.toggle("hidden")
        document.getElementById(openSlide).classList.toggle("hidden")
        openSlide = id
    }
}


function resetESP() {
    sendWebRequest("http://192.168.1.170/reset", "", "POST")
}


updateConfig()