let lastPushId = ""
let arduionoURL
let openSlide = "animationsContainer"
let data
let numberOfLEDS

let var_1 = 0
let speed = 100

fetch("./res/settings.json")
    .then(response => response.json())
    .then(json => {
        console.log(json)
        //data = JSON.parse(json)
        data = json
        arduionoURL = data.settings.ip
        numberOfLEDS = data.settings.num_lights
        console.log(data)
    })

updateCanvas()

function buttonPushAnimation(id) {
    if (id !== lastPushId) {
        document.getElementById(id).style.backgroundColor = "#2c2c36"
        if (lastPushId !== "") {
            document.getElementById(lastPushId).style.backgroundColor = "#252531"
        }
        lastPushId = id

        speed = data.animations[id].speed
        var_1 = data.animations[id].var_1
        document.getElementById("speed").value = speed
        document.getElementById("var_1").value = var_1
        httpGet(arduionoURL + "/" + id)
    }
}


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


function setSpeed(value) {
    if (value !== speed) {
        speed = value
        document.getElementById("speed").value = value
        httpGet(arduionoURL + "/y1:" + value + ":;")
    }
}


function setVar_1(value) {
    if (value !== var_1) {
        var_1 = value
        document.getElementById("var_1").value = value
        try {
            httpGet(arduionoURL + "/y2:" + value + ":;")
        } catch (e) {
        }
    }
}

function setSettings() {
    const nSpeed = document.getElementById("speed").value;
    const nVar_1 = document.getElementById("var_1").value;
    setSpeed(nSpeed)
    setVar_1(nVar_1)
}


function updateCanvas() {
    const canvas = document.getElementById("customCanvas")
    const context = canvas.getContext("2d")
    const numDivs = Math.floor(canvas.getBoundingClientRect().width / numberOfLEDS)
    for (let i = 0; i < numDivs; i++) {
        console.log(i)
        context.fillStyle = "#FFFFFF"
        context.fillRect(i*numberOfLEDS, 0, (i+1)*numberOfLEDS, canvas.getBoundingClientRect().height)
    }
}


function httpGet(theUrl, callback) {
    fetch(theUrl, {
        method: "POST"
    })
        .then(response => {
            if (!response.ok) {
                console.dir("Something went wrong with request: ", response)
            }
        })
        .catch(error => {
            console.log(error)
        })
}
