let ws;
let lastMessageTimestamp = 0;
const IDLE_THRESHOLD_MS = 1000;
const loadingIndicator = document.getElementById("loadingIndicator");

function setLoadingIndicator(visible) {
    if (!loadingIndicator) {
        return;
    }

    loadingIndicator.classList.toggle("hidden", !visible);
}

function updateLoadingState() {
    const isConnected = ws && ws.readyState === WebSocket.OPEN;
    const idle = Date.now() - lastMessageTimestamp >= IDLE_THRESHOLD_MS;

    setLoadingIndicator(isConnected && idle);
}

function connectWS() {
    ws = new WebSocket("ws://" + location.host + "/ws");

    ws.onopen = () => {
        console.log("WebSocket connesso");
        lastMessageTimestamp = Date.now();
        setLoadingIndicator(false);
    };

    ws.onclose = () => {
        console.log("WebSocket disconnesso, retry...");
        setLoadingIndicator(false);
        setTimeout(connectWS, 5000);
    };

    ws.onmessage = (event) => {
        let data;

        try {
            data = JSON.parse(event.data);
        } catch (e) {
            console.error("Invalid JSON received", e);
            return;
        }

        lastMessageTimestamp = Date.now();
        setLoadingIndicator(false);

        document.getElementById("datavalid").textContent = data.datavalid ?? "-";
        document.getElementById("timestamp").textContent = data.timestamp ?? "-";
        document.getElementById("volts_gen").textContent = data.volts_gen ?? "-";
        document.getElementById("eng_rpm").textContent = data.eng_rpm ?? "-";
        document.getElementById("adc_read_time").textContent = data.adc_read_time ?? "-";
        document.getElementById("n_queue_errors").textContent = data.n_queue_errors ?? "-";

        const coils12 = data.coils12 || {};
        const coils34 = data.coils34 || {};

        document.getElementById("coils12_spark_delay").textContent = coils12.spark_delay ?? "-";
        document.getElementById("coils34_spark_delay").textContent = coils34.spark_delay ?? "-";
        document.getElementById("coils12_spark_status").textContent = coils12.spark_status ?? "-";
        document.getElementById("coils34_spark_status").textContent = coils34.spark_status ?? "-";
        document.getElementById("coils12_sstart_status").textContent = coils12.sstart_status ?? "-";
        document.getElementById("coils34_sstart_status").textContent = coils34.sstart_status ?? "-";
        document.getElementById("coils12_peak_p_in").textContent = coils12.peak_p_in ?? "-";
        document.getElementById("coils34_peak_p_in").textContent = coils34.peak_p_in ?? "-";
        document.getElementById("coils12_peak_n_in").textContent = coils12.peak_n_in ?? "-";
        document.getElementById("coils34_peak_n_in").textContent = coils34.peak_n_in ?? "-";
        document.getElementById("coils12_peak_p_out").textContent = coils12.peak_p_out ?? "-";
        document.getElementById("coils34_peak_p_out").textContent = coils34.peak_p_out ?? "-";
        document.getElementById("coils12_peak_n_out").textContent = coils12.peak_n_out ?? "-";
        document.getElementById("coils34_peak_n_out").textContent = coils34.peak_n_out ?? "-";
        document.getElementById("coils12_level_spark").textContent = coils12.level_spark ?? "-";
        document.getElementById("coils34_level_spark").textContent = coils34.level_spark ?? "-";
        document.getElementById("coils12_n_events").textContent = coils12.n_events ?? "-";
        document.getElementById("coils34_n_events").textContent = coils34.n_events ?? "-";
        document.getElementById("coils12_n_missed_firing").textContent = coils12.n_missed_firing ?? "-";
        document.getElementById("coils34_n_missed_firing").textContent = coils34.n_missed_firing ?? "-";
    };
}

function start() {
    fetch("/start");
}

function stop() {
    fetch("/stop");
}

function uploadLittleFS() {
    const fileInput = document.getElementById("littlefsFile");
    const status = document.getElementById("uploadStatus");

    if (!fileInput || fileInput.files.length === 0) {
        if (status) status.textContent = "Select a file first.";
        return;
    }

    const file = fileInput.files[0];
    const formData = new FormData();
    formData.append("file", file, file.name);

    if (status) status.textContent = "Uploading...";

    fetch("/upload", {
        method: "POST",
        body: formData,
    })
        .then((resp) => {
            if (!resp.ok) {
                throw new Error("Upload failed: " + resp.status + " " + resp.statusText);
            }
            return resp.text();
        })
        .then(() => {
            if (status) status.textContent = "Uploaded: " + file.name;
            fileInput.value = "";
        })
        .catch((err) => {
            if (status) status.textContent = err.message;
        });
}

setInterval(updateLoadingState, 200);
connectWS();
