// JS part template Python browser GUI
// Copyright by Anthony Vogelaar, Perth Scotland
// rev 0.10  2026-02-22 initial release

/// ============================= DOM connection ==================================

const   buttons = []
const   edit    = document.getElementById("txt0")
const   memo    = document.getElementById("memo")
const   status  = document.getElementById("status")

buttons.push(document.getElementById("btnTx"))
for (let i=1; i<5; i++) {
    buttons.push(document.getElementById("btnF"+i))
}

// ======================= local =============================

// Button onClick handler and unit test
function onBtnClick(ev) {
    const id = ev.target.id                             // btnTx .. btnF4
    if (id == "btnTx") {
        wsSend({edit: edit.value})
        edit.style.background = "white"
        edit.value = ""
    } else wsSend({btn: id})
}


function onEditInput(ev) {
    edit.style.background = "yellow"
}

// =============================== API ==================================

// add s to memo or clear memo when s = null
function memoAdd(s) {
    if (s) {
        memo.value += s + "\n"
        memo.scrollTop = memo.scrollHeight
    } else memo.value = ''
}


// interpret incoming object commands through wsOnMessage
function doCommand(obj) {
    try {
        for (let [k, v] of Object.entries(obj)) {
            if (k == "memo")   memoAdd(v)
        }
    } catch (error) { 
        console.log("Error: doCommand", error)
    }
}

// ========================= main ==============================

// Add onClick event listener to buttons
function addBtnListener(item, idx) {
    item.addEventListener("click", onBtnClick)
}


function init() {
    buttons.forEach(addBtnListener)			    // button on click handler
    edit.addEventListener("input", onEditInput)
    // wsock.onmessage = wsOnMessage			// WS icoming command handler
}


window.addEventListener("load", init)

// ========================= end ==============================
