let ws;

const JS_MESSAGE = "JS code";
const IN_MESSAGE = "Incoming";

/**
 * Log message
 */
function log(src, txt) {
    const target = document.getElementById("ws_log");
    const msg = document.createElement("div");
    msg.className = "message";
    msg.innerHTML = `<div class='type'>${src}</div><div>${txt}</div>`
    target.insertBefore(msg, target.firstChild);
}

/**
 * Set the state of the WebSocket
 */
function setState(state) {
    document.getElementById("state").innerText = state;
}

/**
 * Initialize WebSocket connection
 */
function connect() {
    disconnect();
    log(JS_MESSAGE, "Initialize connection...");
    ws = new WebSocket("/api/ws");
    setState("Connecting...");
    ws.onopen = function () {
        log(JS_MESSAGE, "Connected to WebSocket !");
        setState("Connected");
    }
    ws.onmessage = function (event) {
        log(IN_MESSAGE, event.data);
    }
    ws.onclose = function () {
        log(JS_MESSAGE, "Disconnected from WebSocket !");
        setState("Disconnected");
    }
    ws.onerror = function (event) {
        console.error("WS Error!", event);
        log(JS_MESSAGE, `Error with websocket! ${event}`);
        setState("Error");
    }
}

/**
 * Close WebSocket connection
 */
function disconnect() {
    if (ws && ws.readyState === WebSocket.OPEN) {
        log(JS_MESSAGE, "Close connection...");
        ws.close();
    }

    setState("Disconnected");
    ws = undefined;
}

/**
 * Clear WS logs
 */
function clearLogs() {
    document.getElementById("ws_log").innerHTML = "";
}