/* javascript for html, CSS and JS template
   Copyright by Anthony Vogelaar, Perth UK
   rev 0.10  2025-02-27  Initial release */

// ====================== Global variables and events ======================

const header = document.getElementById("header")
const wsock  = new WebSocket("ws://" + location.hostname + ":5000/ws")

document.getElementById("btn1").addEventListener("click", onBtnClick)
document.getElementById("btn2").addEventListener("click", onBtnClick)
document.getElementById("btn3").addEventListener("click", onBtnClick)
document.getElementById("btn4").addEventListener("click", onBtnClick)

// =============================== domain =================================

function onLoad(ev) {
   console.log('running ....')
   wsock.onmessage = wsOnMessage
}


function onBtnClick(ev) {
   let id = this.id
   wsSend(id)
}


function wsSend(msg) {
   let obj = {msg: msg}
   wsock.send(JSON.stringify(obj))
}


function wsOnMessage(ev) {
   let obj = JSON.parse(ev.data)
   header.innerText = obj["msg"]
}

// ============================== start ===================================

window.addEventListener("load", onLoad)

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