$(document).ready(function () {
    // Your initialization code here
    //console.log('setting.js is ready!');
    $('#dropdownM1 button').text('');
    $('#dropdownM2 button').text('');
    $('#dropdownM3 button').text('');
    $('#dropdownM4 button').text('');
    $('#dropdownM5 button').text('');
    $('#dropdownM6 button').text('');
    $('#dropdownM7 button').text('');
    $('#dropdownM8 button').text('');

    $('#dropdownM1 .dropdown-menu').empty();
    $('#dropdownM2 .dropdown-menu').empty();
    $('#dropdownM3 .dropdown-menu').empty();
    $('#dropdownM4 .dropdown-menu').empty();
    $('#dropdownM5 .dropdown-menu').empty();
    $('#dropdownM6 .dropdown-menu').empty();
    $('#dropdownM7 .dropdown-menu').empty();
    $('#dropdownM8 .dropdown-menu').empty();

    // Connect to WebSocket at "<current html file>/ws"
    const path = window.location.pathname;
    const ws = new WebSocket('ws://' + window.location.host + path + '/ws');

    ws.onopen = function () {
        //console.log('WebSocket connection opened');
        $('#indicatorDisconnected').addClass('visually-hidden');
        $('#indicatorConnected').removeClass('visually-hidden');
        sendCommand({ command: "getConfig" });

    };

    ws.onmessage = function (event) {
        //console.log('WebSocket message received:', event.data);
        let msg = {};
        try {
            msg = JSON.parse(event.data);
        } catch (e) {
            return;
        }
        if (msg.reply && msg.reply.length > 0) {
            switch (msg.reply) {
                case "getConfig":
                    const configData = JSON.parse(msg.data);
                    //console.log('Config Data:', configData);
                    $('#zelloUsername').val(configData.zelloUsername || '');
                    $('#zelloPassword').val(configData.zelloPassword || '');
                    $('#zelloChannel').val(configData.zelloChannel || '');
                    if ("community" === configData.zelloServer) {
                        $('#zellocommunity').prop('checked', true);
                        $('#zelloWorkNetworkName').val('').prop('disabled', true);
                        $('#zelloEnterpriseServerDomain').val('').prop('disabled', true);
                    } else if ("work" === configData.zelloServer) {
                        $('#zellowork').prop('checked', true);
                        $('#zelloWorkNetworkName').val(configData.zelloWorkNetworkName || '').prop('disabled', false);
                        $('#zelloEnterpriseServerDomain').val('').prop('disabled', true);
                    } else if ("enterprise" === configData.zelloServer) {
                        $('#zelloenterprise').prop('checked', true);
                        $('#zelloWorkNetworkName').val('').prop('disabled', true);
                        $('#zelloEnterpriseServerDomain').val(configData.zelloEnterpriseServerDomain || '').prop('disabled', false);
                    }

                    for (let i = 1; i <= 8; i++) {
                        const dropdownMenu = $(`#dropdownM${i} .dropdown-menu`);
                        const dropdownButton = $(`#dropdownM${i} button`);
                        dropdownMenu.empty();
                        const messages = configData[`messageList`] || [];
                        messages.forEach((msg, idx) => {
                            const item = $('<a class="dropdown-item" href="#"></a>').text(msg);
                            item.on('click', function () {
                                dropdownButton.text(msg);
                            });
                            dropdownMenu.append(item);
                        });
                        // Set button text to selected message if present
                        if (configData[`m${i}`]) {
                            dropdownButton.text(configData[`m${i}`]);
                        } else {
                            dropdownButton.text('');
                        }
                    }
                    break;
                case "setZelloConfig":
                    if (msg.data === "success") {
                        alert('Zello configuration updated successfully.');
                    } else {
                        alert('Failed to update Zello configuration: ' + msg.data);
                    }
                    sendCommand({ command: "getConfig" }); // Refresh config after update
                    break;
                case "setMessageConfig":
                    if (msg.data === "success") {
                        alert('Message configuration updated successfully.');
                    } else {
                        alert('Failed to update Message configuration: ' + msg.data);
                    }
                    sendCommand({ command: "getConfig" }); // Refresh config after update
                    break;
            }
        }


    };

    ws.onclose = function () {
        //console.log('WebSocket connection closed');
        $('#indicatorDisconnected').removeClass('visually-hidden');
        $('#indicatorConnected').addClass('visually-hidden');
    };

    ws.onerror = function (error) {
        console.error('WebSocket error:', error);
    };

    $('#zellocommunity').on('click', function () {
        $('#zelloWorkNetworkName').val('').prop('disabled', true);
        $('#zelloEnterpriseServerDomain').val('').prop('disabled', true);
    });
    $('#zellowork').on('click', function () {
        $('#zelloWorkNetworkName').prop('disabled', false);
        $('#zelloEnterpriseServerDomain').val('').prop('disabled', true);
    });
    $('#zelloenterprise').on('click', function () {
        $('#zelloWorkNetworkName').val('').prop('disabled', true);
        $('#zelloEnterpriseServerDomain').prop('disabled', false);
    });


    $('#btnApplyZello').on('click', function () {
        if (ws.readyState === WebSocket.OPEN) {
            let xx = {
                command: "setZelloConfig"
            };
            let data = {
                ZelloUsername: $('#zelloUsername').val(),
                ZelloPassword: $('#zelloPassword').val(),
                ZelloChannel: $('#zelloChannel').val(),
                ZelloServer: $('#zellocommunity').is(':checked') ? 'community' :
                    $('#zellowork').is(':checked') ? 'work' :
                        $('#zelloenterprise').is(':checked') ? 'enterprise' : ''
            }
            if ($('#zellowork').is(':checked')) {
                data.ZelloWorkNetworkName = $('#zelloWorkNetworkName').val();
            }
            if ($('#zelloenterprise').is(':checked')) {
                data.ZelloEnterpriseServerDomain = $('#zelloEnterpriseServerDomain').val();
            }
            xx.data = JSON.stringify(data);
            sendCommand(xx);
        } else {
            console.warn('WebSocket is not open.');
        }
    });
    $('#btnApplyMessage').on('click', function () {
        if (ws.readyState === WebSocket.OPEN) {
            let data = {
                command: "setMessageConfig",
                data: JSON.stringify({
                    M1: $('#dropdownM1 button').text(),
                    M2: $('#dropdownM2 button').text(),
                    M3: $('#dropdownM3 button').text(),
                    M4: $('#dropdownM4 button').text(),
                    M5: $('#dropdownM5 button').text(),
                    M6: $('#dropdownM6 button').text(),
                    M7: $('#dropdownM7 button').text(),
                    M8: $('#dropdownM8 button').text()
                })

            };
            sendCommand(data);
        } else {
            console.warn('WebSocket is not open.');
        }
    });

    $('#btnUploadContent').on('click', function () {
        const fileInput = document.getElementById('chosenFile');
        if (!fileInput || !fileInput.files.length) {
            alert('Please select a file to upload.');
            return;
        }
        const file = fileInput.files[0];
        const formData = new FormData();
        formData.append('file', file);

        fetch(window.location.pathname + '/upload', {
            method: 'POST',
            body: formData
        })
            .then(response => {
                if (response.ok) {
                    alert('File uploaded successfully.');
                    sendCommand({ command: "getConfig" }); // Refresh config after upload
                } else {
                    alert('File upload failed.');
                }
            })
            .catch(error => {
                console.error('Upload error:', error);
                alert('An error occurred during upload.');
            });
    });

    function sendCommand(cmd) {
        if (ws.readyState === WebSocket.OPEN) {
            ws.send(JSON.stringify(cmd));
        } else {
            console.error('WebSocket is not open. Unable to send command:', JSON.stringify(cmd));
        }
    }
});