const client = io.connect('ws://pi', { path: '/sensehat/socket.io', })

client.on('action', ({ action, x, y, color, pixels }) => {
    var leds = document.querySelectorAll('.led')
    if (color == undefined || color == [0, 0, 0]) color = [255, 255, 255]
    var [r, g, b] = color
    if (r == 0 && g == 0 && b == 0) [r, g, b] = [255, 255, 255]
    switch (action) {
        case 'clear':
            for (let i = 0; i < 64; i++) {
                leds[i].style.backgroundColor = `rgb(${r}, ${g}, ${b})`
            }
            break
        case 'setPixel':
            leds[y * 8 + x].style.backgroundColor = `rgb(${r}, ${g}, ${b})`
            break
        case 'setPixels':
            for (let i = 0; i < 64; i++) {
                var [r, g, b] = pixels[i]
                if (r == 0 && g == 0 && b == 0) [r, g, b] = [255, 255, 255]
                leds[i].style.backgroundColor = `rgb(${r}, ${g}, ${b})`
            }
            break
        default:
            break
    }
})

function setPixel(led) {
    const { x, y } = led.dataset
    const r = Number(red.value)
    const g = Number(green.value)
    const b = Number(blue.value)
    client.emit('action', { action: 'setPixel', x, y, color: [r, g, b] })
}

red.onchange = change_color
green.onchange = change_color
blue.onchange = change_color
function change_color() {
    selected_color.style.backgroundColor = `rgb(${red.value},${green.value},${blue.value})`
}
change_color()
