const eventSource = new EventSource('/events');
eventSource.onmessage = function (event) {
    console.log('Event received:', event.data);
    const data = JSON.parse(event.data);
    document.getElementById('temperature').innerText = data.temperature + ' °C';
    document.getElementById('humidity').innerText = data.humidity + ' %';
};
eventSource.onerror = function (event) {
    console.error('EventSource failed:', event);
};

// function calling all displayPXXX functions based on userSettings.enabled array
// This function will be called after user settings are loaded
function displayAllPlugins() {
    userSettings.enabled.forEach(plugin => {
        // Try to call display function if it exists, otherwise skip
        const fnName = `display${plugin}`;
        if (typeof window[fnName] === 'function') {
            window[fnName]();
        } else {
            console.warn(`Function ${fnName} is not defined`);
        }
    });
}


function loadPluginTiles() {
    const container = document.getElementById("tiles-container");
    container.innerHTML = ""; // clear existing tiles if any

    let index = 0;

    function loadNext() {
        if (index >= userSettings.enabled.length) return;

        const id = userSettings.enabled[index];
        fetch(`/HTML/tile?id=${id}`)
            .then(response => {
                if (!response.ok) throw new Error(`HTTP ${response.status}`);
                return response.text();
            })
            .then(html => {
                const div = document.createElement("div");
                div.innerHTML = html;
                container.appendChild(div);
                index++;
                setTimeout(loadNext, 200); // wait 500ms before loading the next tile
            })
            .catch(error => {
                console.error(`Failed to load tile for ${id}:`, error);
                index++;
                loadNext(); // proceed even on error
            });
    }

    loadNext();
}


function loadPluginScriptsSequentially() {
    let index = 0;
    // set delay for 1000ms   

    function loadNext() {
        if (index >= userSettings.enabled.length) return;

        const script = document.createElement('script');
        script.src = `/HTML/js?id=${userSettings.enabled[index]}`;
        script.onload = () => {
            console.log(`Loaded ${userSettings.enabled[index]}`);
            index++;
            setTimeout(loadNext, 200);
        };
        script.onerror = () => {
            console.error(`Failed to load ${userSettings.enabled[index]}`);
            index++;
            setTimeout(loadNext, 100);
        };

        document.body.appendChild(script);
    }

    loadNext();
}

function toggle(property) {
    const checkbox = document.getElementById(property + '-toggle');
    const url = '/switch?property=' + property;
    fetch(url)
        .then(response => {
            if (response.ok) {
                console.log(property + ' toggled successfully');
                initializePage(); // Refresh the page to reflect changes
            } else {
                console.error('Failed to toggle ' + property);
            }
        })
        .catch(error => console.error('Error:', error));
}

function toggleForm(formId) {
    const form = document.getElementById(formId);
    form.style.display = form.style.display === 'none' ? 'block' : 'none';
}

function toggleEspInfo() {
    const espInfoDiv = document.getElementById('esp-info');
    espInfoDiv.style.display = (espInfoDiv.style.display === 'none' || espInfoDiv.style.display === '') ? 'block' : 'none';
}

window.onload = initializePage;