/**
 * @typedef {Object} LanguageBank
 * @property {number} index
 * @property {string} tag
 * @property {string} language
 * 
 */

/** List of Languagebank data loaded from server
 * @type {LanguageBank[]}
 */
window.languagebankdata = [];
/**
 * Currently selected languagebank row in the table
 * @type {JQuery<HTMLElement>|null}
 */
window.selectedlanguagerow = null;

/**
 * Fill languagebank table body with values
 * @param {LanguageBank[]} vv values to fill
 */
function fill_languagebanktablebody(vv) {
    $('#languagebanktablebody').empty();
    if (!Array.isArray(vv) || vv.length === 0) return;
    vv.forEach(item => {
        const row = `<tr>
                     <td>${item.index}</td>
                     <td>${item.tag}</td>
                     <td>${item.language}</td>
                     </tr>`;
        $('#languagebanktablebody').append(row);
        let $addedrow = $('#languagebanktablebody tr:last');
        $addedrow.click(function () {
            if (window.selectedlanguagerow) {
                window.selectedlanguagerow.find('td').css('background-color', '');
                if (window.selectedlanguagerow.is($(this))) {
                    window.selectedlanguagerow = null;
                    $('#btnRemove').prop('disabled', true);
                    $('#btnEdit').prop('disabled', true);
                    return;
                }
            }
            $addedrow.find('td').css('background-color', '#ffeeba');
            window.selectedlanguagerow = $addedrow;
            $('#btnRemove').prop('disabled', false);
            $('#btnEdit').prop('disabled', false);
        });
    });
    $('#tablesize').text("Table Size: " + vv.length);
}

/**
 * Reload language bank from server
 * @param {string} APIURL API URL endpoint, default "LanguageLink/"
 */
function reloadLanguageBank(APIURL = "LanguageLink/") {
    window.languagebankdata = [];
    fetchAPI(APIURL + "List", "GET", {}, null, (okdata) => {
        if (Array.isArray(okdata)) {
            window.languagebankdata.push(...okdata);
            window.selectedlanguagerow = null;
            fill_languagebanktablebody(window.languagebankdata);
        }
    }, (errdata) => {
        alert("Error loading languagebank : " + errdata.message);
    });
}

$(document).ready(function () {
    console.log('languagebank.js loaded');

    $('#languagebanktablebody').empty();
    window.selectedlanguagerow = null;
    let $btnClear = $('#btnClear');
    let $btnAdd = $('#btnAdd');
    let $btnRemove = $('#btnRemove');
    let $btnEdit = $('#btnEdit');
    let $btnExport = $('#btnExport');
    let $btnImport = $('#btnImport');
    $btnRemove.prop('disabled', true);
    $btnEdit.prop('disabled', true);
    let APIURL = "LanguageLink/";
    let $findlanguage = $('#findlanguage');
    let $modal = $('#languagemodal');
    let $langid = $modal.find('#languagelinkindex');
    let $langtag = $modal.find('#languagelinktag');
    let $cbInd = $modal.find('#langId');
    let $cbLocal = $modal.find('#langLocal');
    let $cbEn = $modal.find('#langEn');
    let $cbArb = $modal.find('#langArb');
    let $cbJap = $modal.find('#langJap');
    let $cbChi = $modal.find('#langChi');

    function clearLanguageModal() {
        $langid.prop('disabled', true).val('');
        $langtag.val('');
        $cbInd.prop('checked', false);
        $cbLocal.prop('checked', false);
        $cbEn.prop('checked', false);
        $cbArb.prop('checked', false);
        $cbJap.prop('checked', false);
        $cbChi.prop('checked', false);
    }

    $findlanguage.on('input', function () {
        let searchTerm = $findlanguage.val().toLowerCase();
        if (searchTerm.length > 0) {
            window.selectedlanguagerow = null;
            let filtered = window.languagebankdata.filter(item => item.tag.toLowerCase().includes(searchTerm) || item.language.toLowerCase().includes(searchTerm));
            fill_languagebanktablebody(filtered);
        } else {
            window.selectedlanguagerow = null;
            fill_languagebanktablebody(window.languagebankdata);
        }
    });

    reloadLanguageBank(APIURL);
    $btnClear.click(() => {
        DoClear(APIURL, "LanguageLink", (okdata) => {
            reloadLanguageBank(APIURL);
            alert("Success clear languageLink : " + okdata.message);
        }, (errdata) => {
            alert("Error clear languageLink : " + errdata.message);
        });

    });
    $btnAdd.click(() => {
        // show modal with id 'languagemodal'
        $modal.modal('show');
        clearLanguageModal();

        // save button click event
        $modal.off('click.languagelinksave').on('click.languagelinksave', '#languagelinksave', function () {
            const tag = $langtag.val();
            const langs = [];
            if ($cbInd.is(':checked')) langs.push('INDONESIA');
            if ($cbLocal.is(':checked')) langs.push('LOCAL');
            if ($cbEn.is(':checked')) langs.push('ENGLISH');
            if ($cbArb.is(':checked')) langs.push('ARABIC');
            if ($cbJap.is(':checked')) langs.push('JAPANESE');
            if ($cbChi.is(':checked')) langs.push('CHINESE');

            if (tag.length === 0) {
                alert("Tag cannot be empty");
                return;
            }
            if (langs.length === 0) {
                alert("At least one language must be selected");
                return;
            }

            const langString = langs.join(';');
            let ll = {
                tag: tag,
                language: langString
            }
            fetchAPI(APIURL + "Add", "POST", {}, ll, (okdata) => {
                alert("Success add language : " + okdata.message);
                reloadLanguageBank(APIURL);
            }, (errdata) => {
                alert("Error add language : " + errdata.message);
            });
            $modal.modal('hide');


        });
        // close button click event
        $modal.off('click.languagelinkclose').on('click.languagelinkclose', '#languagelinkclose', function () {
            $modal.modal('hide');
        });
    });
    $btnRemove.click(() => {
        if (window.selectedlanguagerow) {
            let cells = window.selectedlanguagerow.find('td');
            /** @type {Language} */
            let ll = {
                index: Number(cells.eq(0).text()),
                tag: cells.eq(1).text(),
                language: cells.eq(2).text()
            }
            if (confirm(`Are you sure to delete language [${ll.index}] Tag=${ll.tag} Language=${ll.language}?`)) {
                fetchAPI(APIURL + "DeleteByIndex/" + ll.index, "DELETE", {}, null, (okdata) => {
                    reloadLanguageBank(APIURL);
                    alert("Success delete language : " + okdata.message);
                }, (errdata) => {
                    alert("Error delete language : " + errdata.message);
                });
            }
        }
    });
    $btnEdit.click(() => {
        if (window.selectedlanguagerow) {
            let cells = window.selectedlanguagerow.find('td');
            /** @type {Language} */
            let ll = {
                index: Number(cells.eq(0).text()),
                tag: cells.eq(1).text(),
                language: cells.eq(2).text()
            }
            if (confirm(`Are you sure to edit language [${ll.index}] Tag=${ll.tag} Language=${ll.language}?`)) {

                clearLanguageModal();
                $langid.val(ll.index);
                $langtag.val(ll.tag);
                let langs = ll.language.toUpperCase().split(';');
                $cbInd.prop('checked', langs.includes('INDONESIA'));
                $cbLocal.prop('checked', langs.includes('LOCAL'));
                $cbEn.prop('checked', langs.includes('ENGLISH'));
                $cbArb.prop('checked', langs.includes('ARABIC'));
                $cbJap.prop('checked', langs.includes('JAPANESE'));
                $cbChi.prop('checked', langs.includes('CHINESE'));
                $modal.modal('show');
                // save button click event
                $modal.off('click.languagelinksave').on('click.languagelinksave', '#languagelinksave', function () {
                    const tag = $langtag.val();
                    const langs = [];
                    if ($cbInd.is(':checked')) langs.push('INDONESIA');
                    if ($cbLocal.is(':checked')) langs.push('LOCAL');
                    if ($cbEn.is(':checked')) langs.push('ENGLISH');
                    if ($cbArb.is(':checked')) langs.push('ARABIC');
                    if ($cbJap.is(':checked')) langs.push('JAPANESE');
                    if ($cbChi.is(':checked')) langs.push('CHINESE');
                    if (tag.length === 0) {
                        alert("Tag cannot be empty");
                        return;
                    }
                    if (langs.length === 0) {
                        alert("At least one language must be selected");
                        return;
                    }
                    const langString = langs.join(';');
                    if (ll.tag === tag && ll.language === langString) {
                        alert("No changes detected");
                        $modal.modal('hide');
                        return;
                    }

                    ll.tag = tag;
                    ll.language = langString;
                    fetchAPI(APIURL + "UpdateByIndex/" + ll.index, "PATCH", {}, ll, (okdata) => {
                        reloadLanguageBank(APIURL);
                        alert("Success edit language : " + okdata.message);
                    }, (errdata) => {
                        alert("Error edit language : " + errdata.message);
                    });

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


            }
        }
    });
    $btnExport.click(() => {
        DoExport(APIURL, "languagebank.xlsx", {});

    });
    $btnImport.click(() => {
        DoImport(APIURL, (okdata) => {
            reloadLanguageBank(APIURL);
            alert("Success import languagebank : " + okdata.message);
        }, (errdata) => {
            alert("Error importing languagebank from XLSX : " + errdata.message);
        });

    });
});