/**
 * @typedef {Object} UserDB
 * @property {number} index Index number
 * @property {string} username Username
 * @property {string} password Password (plain)
 * @property {string} location Location
 * @property {string} airline_tags Airline variable tags (string) separated by semicolon ;
 * @property {string} city_tags City variable tags (string) separated by semicolon ;
 * @property {string} messagebank_ann_id Messagebank announcement ID (number) separated by semicolon ;
 * @property {string} broadcastzones Broadcast zones description (string) separated by semicolon ;
 */

/** List of UserDB data loaded from server
 * @type {UserDB[]}
 */
window.userdb = [];

/**
 * Currently selected user row in table
 * @type {JQuery<HTMLElement>|null}
 */
window.selecteduserrow = null;

/**
 * @typedef {Object} KeyValueMessage
 * @property {string} key
 * @property {string} value
 */

/**
 * List of airline tags loaded from server
 * @type {KeyValueMessage[]}
 */
window.airlinetags = [];
/**
 * List of city tags loaded from server
 * @type {KeyValueMessage[]}
 */
window.citytags = [];
/**
 * List of message bank IDs loaded from server
 * @type {KeyValueMessage[]}
 */
window.messagebankids = [];
/**
 * List of broadcast zones description loaded from server
 * @type {string[]}
 */
window.broadcastzones = [];

/**
 * Get Messagebank ANN_IDs from server
 */
function get_messagebankids() {
    window.messagebankids = [];
    fetchAPI("MessageBank/" + "MessageIDs", "GET", {}, null, (okdata) => {
        if (Array.isArray(okdata)) {
            window.messagebankids.push(...okdata);
        }
    }, (errdata) => {
        alert("Error loading message bank IDs : " + errdata.message);
    });
}

/**
 * Get Airline Tags from server
 */
function get_airlinetags() {
    window.airlinetags = [];
    fetchAPI("SoundBank/" + "AirlineTags", "GET", {}, null, (okdata) => {
        if (Array.isArray(okdata)) {
            window.airlinetags.push(...okdata);
        }
    }, (errdata) => {
        alert("Error loading airline tags : " + errdata.message);
    });
}

/**
 * Get City Tags from server
 */
function get_citytags() {
    window.citytags = [];
    fetchAPI("SoundBank/" + "CityTags", "GET", {}, null, (okdata) => {
        if (Array.isArray(okdata)) {
            window.citytags.push(...okdata);
        }
    }, (errdata) => {
        alert("Error loading city tags : " + errdata.message);
    });
}

/**
 * Get Broadcast Zones descriptions from server
 */
function get_broadcastzones_descriptions() {
    window.broadcastzones = [];
    fetchAPI("BroadcastZones/" + "BroadcastZoneDescriptions", "GET", {}, null, (okdata) => {
        if (Array.isArray(okdata)) {
            window.broadcastzones.push(...okdata);
        }
    }, (errdata) => {
        alert("Error loading broadcast zones : " + errdata.message);
    });
}

/**
 * Fill user table body with values
 * @param {UserDB[]} vv values to fill
 */
function fill_usertablebody(vv) {
    $('#usertablebody').empty();

    if (!Array.isArray(vv) || vv.length === 0) {
        $('#btnExport').prop('disabled', true);
        return;
    }
    vv.forEach(item => {
        const row = `<tr>
                     <td>${item.index}</td>
                     <td>${item.username}</td>
                     <td>${item.location}</td>
                     <td>${item.airline_tags}</td>
                     <td>${item.city_tags}</td>
                     <td>${item.messagebank_ann_id}</td>
                     <td>${item.broadcastzones}</td>
                     </tr>`;
        $('#usertablebody').append(row);
        let $addedrow = $('#usertablebody tr:last');
        $addedrow.off('click').on('click', function () {
            if (window.selecteduserrow) {
                window.selecteduserrow.find('td').css('background-color', '');
                if (window.selecteduserrow.is($(this))) {
                    window.selecteduserrow = null;
                    $('#btnRemove').prop('disabled', true);
                    $('#btnEdit').prop('disabled', true);
                    return;
                }
            }
            $(this).find('td').css('background-color', '#ffeeba');
            window.selecteduserrow = $(this);
            $('#btnRemove').prop('disabled', false);
            $('#btnEdit').prop('disabled', false);
        });
    });
    $('#tablesize').text("Table Size: " + vv.length);
    $('#btnExport').prop('disabled', false);
}

/**
 * Reload UserDB from server with date and filter
 * @param {String} APIURL API URL endpoint , default "UserManagement/"
 */
function reloaduserDB(APIURL = "UserManagement/") {
    window.userdb = [];
    fetchAPI(APIURL + "List", "GET", {}, null, (okdata) => {
        if (Array.isArray(okdata)) {
            window.userdb.push(...okdata);
            fill_usertablebody(window.userdb);
        }
    }, (errdata) => {
        alert("Error loading user database : " + errdata.message);
    });
}

$(document).ready(function () {
    console.log("usermanagement.js ready");
    get_airlinetags();
    get_citytags();
    get_messagebankids();
    get_broadcastzones_descriptions();

    let APIURL = "UserManagement/";

    function clearAddModal() {
        $('#modalindex').val("");
        $('#modalusername').val("");
        $('#modalpassword').val("");
        $('#modalverifypassword').val("");
        $('#modalairlinetags').val("");
        $('#modalcitytags').val("");
        $('#modalmessagebank').val("");
        $('#modalbroadcastzones').val("");
        $('#modallocation').val("");
    }

    function fill_citylist() {
        $('#citylist').empty();
        citytags.forEach(tag => {
            let value = `${tag.value} [${tag.key}]`;
            const row = `<div class="form-check">
                         <input class="form-check-input citytagcheckbox" type="checkbox" value="${tag.key}" id="citytag_${tag.key}">
                         <label class="form-check-label" for="citytag_${tag.key}">
                           ${value}
                         </label>
                       </div>`;
            $('#citylist').append(row);
        });
    }

    function fill_airlinelist() {
        $('#airlinelist').empty();
        airlinetags.forEach(tag => {
            let value = `${tag.value} [${tag.key}]`;
            const row = `<div class="form-check">
                         <input class="form-check-input airlinetagcheckbox" type="checkbox" value="${tag.key}" id="airlinetag_${tag.key}">
                         <label class="form-check-label" for="airlinetag_${tag.key}">
                           ${value}
                         </label>
                       </div>`;
            $('#airlinelist').append(row);
        });
    }

    // broadcast zone selection modal elements

    function fill_broadcastzonelist() {
        $('#broadcastzonelist').empty();
        broadcastzones.forEach(desc => {
            const row = `<div class="form-check">
                         <input class="form-check-input broadcastzonecheckbox" type="checkbox" value="${desc}" id="broadcastzone_${desc}">
                         <label class="form-check-label" for="broadcastzone_${desc}">
                           ${desc}
                         </label>
                       </div>`;
            $('#broadcastzonelist').append(row);
        });
    }


    // messagebank selection modal elements

    function fill_messagebanklist() {
        $('#messagebanklist').empty();
        messagebankids.forEach(id => {
            let value = `${id.value} [${id.key}]`;
            const row = `<div class="form-check">
                         <input class="form-check-input messagebankidcheckbox" type="checkbox" value="${id.key}" id="messagebankid_${id.key}">
                         <label class="form-check-label" for="messagebankid_${id.key}">
                           ${value}
                         </label>
                       </div>`;
            $('#messagebanklist').append(row);
        });
    }


    $('#usertablebody').empty();
    reloaduserDB();
    $('#finduser').off('input').on('input', function () {
        let searchTerm = $(this).val().toLowerCase();
        if (searchTerm.length > 0) {
            let filteredUsers = window.userdb.filter(user =>
                user.username.toLowerCase().includes(searchTerm) ||
                user.airline_tags.toLowerCase().includes(searchTerm) ||
                user.city_tags.toLowerCase().includes(searchTerm)
                //user.messagebank_ann_id.toLowerCase().includes(searchTerm) ||
                //user.broadcastzones.toLowerCase().includes(searchTerm)
            );
            fill_usertablebody(filteredUsers);
        } else {
            fill_usertablebody(window.userdb);
        }

    });

    /**
     * Show modal dialog for soundbank, messagebank, broadcastzone selection
     * @param {boolean} editmode if true, edit mode, else add mode
     * @param {number} index index of user to edit, default 0
     */
    function modalshow(editmode = false, index=0) {
        // event on click btnShowSoundbankModal
        $('#btnShowSoundbankModal').off('click').on('click', function () {
            $('#soundbankmodal').modal('show');
            fill_citylist();
            fill_airlinelist();

            let airline = $('#modalairlinetags').val().trim();
            let city = $('#modalcitytags').val().trim();
            if (airline.length > 0) {
                let airlinekeys = airline.split(";");
                $('#airlinelist input[type=checkbox]').each(function () {
                    let tag = $(this).val();
                    if (airlinekeys.includes(tag)) {
                        $(this).prop('checked', true);
                    }
                });
            }
            if (city.length > 0) {
                let citykeys = city.split(";");
                $('#citylist input[type=checkbox]').each(function () {
                    let tag = $(this).val();
                    if (citykeys.includes(tag)) {
                        $(this).prop('checked', true);
                    }
                });
            }

            $('#soundbankmodal').off('click.soundbankselectionsave').on('click.soundbankselectionsave', '#soundbankselectionsave', function () {
                let selected_airlinetags = [];
                $('#airlinelist input[type=checkbox]:checked').each(function () {
                    selected_airlinetags.push($(this).val());
                });
                let selected_citytags = [];
                $('#citylist input[type=checkbox]:checked').each(function () {
                    selected_citytags.push($(this).val());
                });

                //console.log("Selected airline tags: ", selected_airlinetags);
                //console.log("Selected city tags: ", selected_citytags);

                if (selected_airlinetags.length == 0 || selected_citytags.length == 0) {
                    alert("Please select at least one airline tag and one city tag.");
                    return;
                }

                let airlinevalue = selected_airlinetags.join(";");
                let cityvalue = selected_citytags.join(";");
                $('#modalairlinetags').val(airlinevalue);
                $('#modalcitytags').val(cityvalue);


                $('#soundbankmodal').modal('hide');
            });
            $('#soundbankmodal').off('click.soundbankselectionclose').on('click.soundbankselectionclose', '#soundbankselectionclose', function () {
                $('#soundbankmodal').modal('hide');
            });
        });
        // event on click btnShowMessagebankModal
        $('#btnShowMessagebankModal').off('click').on('click', function () {
            $('#messagebankmodal').modal('show');
            fill_messagebanklist();
            let messagebank = $('#modalmessagebank').val().trim();
            if (messagebank.length > 0) {
                let messagebankkeys = messagebank.split(";");
                $('#messagebanklist input[type=checkbox]').each(function () {
                    let id = $(this).val();
                    if (messagebankkeys.includes(id)) {
                        $(this).prop('checked', true);
                    }
                });
            }

            $('#messagebankmodal').off('click.messagebankselectionsave').on('click.messagebankselectionsave', '#messagebankselectionsave', function () {
                let selected_messagebankids = [];
                $('#messagebanklist input[type=checkbox]:checked').each(function () {
                    selected_messagebankids.push($(this).val());
                });
                //console.log("Selected message bank IDs: ", selected_messagebankids);
                if (selected_messagebankids.length == 0) {
                    alert("Please select at least one message bank ID.");
                    return;
                }
                let messagebankvalue = selected_messagebankids.join(";");
                $('#modalmessagebank').val(messagebankvalue);

                $('#messagebankmodal').modal('hide');
            });
            $('#messagebankmodal').off('click.messagebankselectionclose').on('click.messagebankselectionclose', '#messagebankselectionclose', function () {
                $('#messagebankmodal').modal('hide');
            });
        });
        // event on click btnShowBroaadcastZoneModal
        $('#btnShowBroaadcastZoneModal').off('click').on('click', function () {
            $('#broadcastzonemodal').modal('show');
            fill_broadcastzonelist();
            let broadcastzones = $('#modalbroadcastzones').val().trim();
            if (broadcastzones.length > 0) {
                let broadcastzonesvalues = broadcastzones.split(";");
                $('#broadcastzonelist input[type=checkbox]').each(function () {
                    let desc = $(this).val();
                    if (broadcastzonesvalues.includes(desc)) {
                        $(this).prop('checked', true);
                    }
                });
            }
            $('#broadcastzonemodal').off('click.broadcastzoneselectionsave').on('click.broadcastzoneselectionsave', '#broadcastzoneselectionsave', function () {
                let selected_broadcastzones = [];
                $('#broadcastzonelist input[type=checkbox]:checked').each(function () {
                    selected_broadcastzones.push($(this).val());
                });
                //console.log("Selected broadcast zones: ", selected_broadcastzones);
                if (selected_broadcastzones.length == 0) {
                    alert("Please select at least one broadcast zone.");
                    return;
                }
                let broadcastzonesvalue = selected_broadcastzones.join(";");
                $('#modalbroadcastzones').val(broadcastzonesvalue);
                $('#broadcastzonemodal').modal('hide');
            });
            $('#broadcastzonemodal').off('click.broadcastzoneselectionclose').on('click.broadcastzoneselectionclose', '#broadcastzoneselectionclose', function () {
                $('#broadcastzonemodal').modal('hide');
            });
        });

        // event on Click save button
        $('#addmodal').off('click.usermanagementsave').on('click.usermanagementsave', '#usermanagementsave', function () {
            let username = $('#modalusername').val().trim();
            let password = $('#modalpassword').val();
            let verifypassword = $('#modalverifypassword').val();
            let location = $('#modallocation').val().trim();
            let airline_tags = $('#modalairlinetags').val().trim();
            let city_tags = $('#modalcitytags').val().trim();
            let messagebank_ann_id = $('#modalmessagebank').val().trim();
            let broadcastzones = $('#modalbroadcastzones').val().trim();

            if (username.length === 0) {
                alert("Username cannot be empty");
                return;
            }
            if (password.length === 0 || verifypassword.length === 0) {
                alert("Password cannot be empty");
                return;
            }
            if (password !== verifypassword) {
                alert("Password and Verify Password do not match");
                return;
            }
            if (airline_tags.length === 0) {
                alert("Airline tags cannot be empty");
                return;
            }
            if (city_tags.length === 0) {
                alert("City tags cannot be empty");
                return;
            }
            if (messagebank_ann_id.length === 0) {
                alert("Message bank ANN_ID cannot be empty");
                return;
            }
            if (broadcastzones.length === 0) {
                alert("Broadcast zones cannot be empty");
                return;
            }

            /**
             * @type {UserDB}
             */
            let ll = {
                index: index,
                username: username,
                password: password,
                location: location,
                airline_tags: airline_tags,
                city_tags: city_tags,
                messagebank_ann_id: messagebank_ann_id,
                broadcastzones: broadcastzones
            }

            if (editmode) {
                fetchAPI(APIURL + "UpdateByIndex/" + index, "PATCH", {}, ll, (okdata) => {
                    alert("Success update User : " + okdata.message);
                    reloaduserDB();
                }, (errdata) => {
                    alert("Error update User : " + errdata.message);
                });

            } else {
                fetchAPI(APIURL + "Add", "POST", {}, ll, (okdata) => {
                    alert("Success add User : " + okdata.message);
                    reloaduserDB();
                }, (errdata) => {
                    alert("Error add User : " + errdata.message);
                });
            }


            $('#addmodal').modal('hide');
        });
        // event on Click close button
        $('#addmodal').off('click.usermanagementclose').on('click.usermanagementclose', '#usermanagementclose', function () {
            $('#addmodal').modal('hide');
        });
    }

    $('#btnClear').off('click').on('click', function () {
        DoClear(APIURL, "UserManagement", (okdata) => {
            reloaduserDB();
            alert("Success clear user management : " + okdata.message);
        }, (errdata) => {
            alert("Error clear user management : " + errdata.message);
        });
    });
    $('#btnAdd').off('click').on('click', () => {
        $('#addmodal').modal('show');
        clearAddModal();
        modalshow(false,0);
    });
    $('#btnRemove').off('click').on('click', () => {
        if (window.selecteduserrow) {
            let cells = window.selecteduserrow.find('td');
            /** @type {UserDB} */
            let user = {
                index: parseInt(cells.eq(0).text()),
                username: cells.eq(1).text(),
                password: cells.eq(2).text(),
                airline_tags: cells.eq(3).text(),
                city_tags: cells.eq(4).text(),
                messagebank_ann_id: cells.eq(5).text(),
                broadcastzones: cells.eq(6).text()
            }
            if (confirm(`Are you sure to delete user [${user.index}] Username=${user.username} ?`)) {
                fetchAPI(APIURL + "DeleteByIndex/" + user.index, "DELETE", {}, null, (okdata) => {
                    reloaduserDB();
                    alert("Success delete user : " + okdata.message);
                }, (errdata) => {
                    alert("Error delete user : " + errdata.message);
                });
            }
        } else {
            alert("No user selected");
        }
    });
    $('#btnEdit').off('click').on('click', () => {
        if (window.selecteduserrow) {
            let cells = window.selecteduserrow.find('td');
            let index = parseInt(cells.eq(0).text());
            if (isNaN(index) || index <= 0) {
                alert("Invalid user index");
                return;
            }
            /** @type {UserDB} */
            let user = window.userdb.find(u => u.index === index);
            if (!user) {
                alert("User not found");
                return;
            }
            if (confirm(`Are you sure to edit user [${user.index}] Username=${user.username} ?`)) {
                $('#addmodal').modal('show');
                // fill modal with user data
                $('#modalindex').val(user.index);
                $('#modalusername').val(user.username);
                $('#modalpassword').val(user.password);
                $('#modalverifypassword').val(user.password);
                $('#modallocation').val(user.location);
                $('#modalairlinetags').val(user.airline_tags);
                $('#modalcitytags').val(user.city_tags);
                $('#modalmessagebank').val(user.messagebank_ann_id);
                $('#modalbroadcastzones').val(user.broadcastzones);
                modalshow(true, user.index);

            }
        } else {
            alert("No user selected");
        }
    });
    $('#btnExport').off('click').on('click', () => {
        DoExport(APIURL, "user.xlsx", {});
    });
    $('#btnImport').off('click').on('click', () => {
        DoImport(APIURL, (okdata) => {
            reloaduserDB();
            alert("Success import user : " + okdata.message);
        }, (errdata) => {
            alert("Error importing user from XLSX : " + errdata.message);
        });
    });
});