/**
 * @typedef {Object} SoundChannel
 * @property {number} index - The index of the sound channel.
 * @property {string} channel - The name of the sound channel.
 * @property {string} ip - The IP address associated with the sound channel.
 */

/**
 * @type {SoundChannel[]}
 */
window.soundChannels = [];

// Currently selected sound channel row in the table
window.selectedSoundChannel = null;

/**
 * Fills the sound channel table body with the provided data.
 * @param {SoundChannel[]} vv Sound channel data to populate the table.
 */
function fill_soundchanneltablebody(vv) {
    let $btnEditSoundChannel = $('#btnEditSoundChannel');
    let $tablesizeSoundChannel = $('#tablesizeSoundChannel');
    $('#soundchanneltablebody').empty();
    
    $tablesizeSoundChannel.text('Table Length : N/A');
    if (!Array.isArray(vv) || vv.length === 0) return;

    vv.forEach(item => {
        const row = `<tr>
            <td>${item.index}</td>
            <td>${item.channel}</td>
            <td>${item.ip}</td>
        </tr>`;
        $('#soundchanneltablebody').append(row);
        let $addedrow = $('#soundchanneltablebody tr:last');
        $addedrow.off('click').on('click', function () {
            if (selectedSoundChannel) {
                selectedSoundChannel.find('td').css('background-color', '');
                if (selectedSoundChannel.is($(this))) {
                    selectedSoundChannel = null;
                    $btnEditSoundChannel.prop('disabled', true);
                    return;
                }
            }
            $(this).find('td').css('background-color', '#ffeeba');
            selectedSoundChannel = $(this);
            $btnEditSoundChannel.prop('disabled', false);
        });
    });
    $tablesizeSoundChannel.text("Table Size: " + vv.length);
}

/**
 * Reload sound channels from server
 * @param {String} APIURL API URL endpoint (default "SoundChannel/")
 */
function reloadSoundChannel(APIURL = "SoundChannel/") {
    window.soundChannels = [];
    fetchAPI(APIURL + "List", "GET", {}, null, (okdata) => {
        if (Array.isArray(okdata)) {
            //console.log("reloadSoundChannel : ", okdata)
            window.soundChannels.push(...okdata);
            fill_soundchanneltablebody(window.soundChannels);
        } else console.log("reloadSoundChannel: okdata is not array");
    }, (errdata) => {
        alert("Error loading sound channels : " + errdata.message);
    });
}
    
$(document).ready(function () {
    console.log("soundchannel.js loaded successfully");
    let $soundchannelmodal = $('#soundchannelmodal');
    let $soundchannelindex = $soundchannelmodal.find('#soundchannelindex');
    let $soundchanneldescription = $soundchannelmodal.find('#soundchanneldescription');
    let $soundchannelip = $soundchannelmodal.find('#soundchannelip');

    let $btnReinitializeSoundChannel = $('#btnReinitializeSoundChannel');
    let $btnEditSoundChannel = $('#btnEditSoundChannel');
    let $btnExportSoundChannel = $('#btnExportSoundChannel');
    let $btnImportSoundChannel = $('#btnImportSoundChannel');
    let $findsoundchannel = $('#findsoundchannel');
    $btnEditSoundChannel.prop('disabled', true);
    let API_SoundChannel = "SoundChannel/";

    $findsoundchannel.off('input').on('input', function () {
        let searchTerm = $(this).val().toLowerCase();
        if (searchTerm.length==0){
            window.selectedSoundChannel = null;
            fill_soundchanneltablebody(window.soundChannels);
        } else {
            window.selectedSoundChannel = null;
            let filteredChannels = window.soundChannels.filter(xx =>
                xx.index.toString().includes(searchTerm) ||
                xx.channel.toLowerCase().includes(searchTerm) ||
                xx.ip.toLowerCase().includes(searchTerm)
            );
            fill_soundchanneltablebody(filteredChannels);
        }
    });

    /**
     * Clear sound channel modal inputs
     */
    function clearSoundChannelModal() {
        $soundchannelindex.val('');
        $soundchanneldescription.val('');
        $soundchannelip.val('');
    }

    reloadSoundChannel(API_SoundChannel);
    $btnReinitializeSoundChannel.off('click').on('click', () => {
        DoClear(API_SoundChannel, "SoundChannels", (okdata) => {
            reloadSoundChannel(API_SoundChannel);
            alert("Success clear sound channels: " + okdata.message);
        }, (errdata) => {
            alert("Error clear sound channels: " + errdata.message);
        });
    });
    $btnEditSoundChannel.off('click').on('click', () => {
        if (selectedSoundChannel) {
            let cells = selectedSoundChannel.find('td');
            /** @type {SoundChannel} */
            let sc = {
                index: parseInt(cells.eq(0).text(), 10),
                description: cells.eq(1).text(),
                ip: cells.eq(2).text()
            };
            if (confirm(`Are you sure to edit sound channel [${sc.index}] Description=${sc.description} IP=${sc.ip}?`)) {
                $soundchannelmodal.modal('show');
                clearSoundChannelModal();
                $soundchannelindex.val(sc.index).prop('disabled', true);
                $soundchanneldescription.val(sc.description);
                $soundchannelip.val(sc.ip);

                // Handle save changes
                $soundchannelmodal.off('click.soundchannelsave').on('click.soundchannelsave', '#soundchannelsave', function () {
                    let newsc = {
                        index: parseInt($soundchannelindex.val(), 10),
                        description: $soundchanneldescription.val(),
                        ip: $soundchannelip.val()
                    };
                    if (newsc.description.trim().length === 0) {
                        alert("Description cannot be empty");
                        return;
                    }
                    if (newsc.ip.trim().length === 0) {
                        alert("IP cannot be empty");
                        return;
                    }
                    if (newsc.description===sc.description && newsc.ip===sc.ip){
                        alert("No changes detected");
                        return;
                    }

                    

                    fetchAPI(API_SoundChannel + "UpdateByIndex/" + newsc.index, "PATCH", {}, newsc, (okdata) => {
                        reloadSoundChannel(API_SoundChannel);
                        alert("Success edit sound channel: " + okdata.message);
                    }, (errdata) => {
                        alert("Error edit sound channel: " + errdata.message);
                    });
                    $soundchannelmodal.modal('hide');
                    
                    
                });
                $soundchannelmodal.off('click.soundchannelclose').on('click.soundchannelclose', '#soundchannelclose', function () {
                    $soundchannelmodal.modal('hide');
                });
            }
        }
    });
    $btnExportSoundChannel.off('click').on('click', () => {
        DoExport(API_SoundChannel, "soundchannels.xlsx", {});
    });

    $btnImportSoundChannel.off('click').on('click', () => {
        DoImport(API_SoundChannel, (okdata) => {
            reloadSoundChannel(API_SoundChannel);
            alert("Success import sound channels: " + okdata.message);
        }, (errdata) => {
            alert("Error importing sound channels from XLSX: " + errdata.message);
        });
    });
});