async function openImportCodebookModal(title, tableTitles, tableDataNames, getImportCodebookItemsUrl, importCodebookItemsUrl, helpUrl, localization, userLocalization, onSuccess, beforeDataSend, additionalFilters, onLoad) {
    let $codebookModalFilters = generateCodebookFilter(tableDataNames, getImportCodebookItemsUrl, userLocalization, localization, beforeDataSend, additionalFilters, onLoad);
    let codebookTable = generateCodebookTable(tableTitles, localization);

    let $codebookModalBody = $("<div style='overflow-x: hidden;'></div>");
    $codebookModalBody.append($codebookModalFilters);
    $codebookModalBody.append(codebookTable);

    $().customModal({
        showCloseButton: true,
        closeOtherModals: false,
        minHeight: "70%",
        minWidth: "200px",
        maxWidth: "800px",
        width: "80%",
        type: "modal",
        id: "codebookImportModal",
        help: helpUrl,
        title: title,
        resizable: true,
        content: $codebookModalBody,
        buttons: [
            {
                text: localization.importIntoCodebook,
                icon: 'fa fa-file-import',
                type: 'primary',
                closeOnAction: true,
                action: async function () { await importCodebook("codebookImportModal", importCodebookItemsUrl, onSuccess, beforeDataSend); }
            }
        ],
        onOpen: function () {
            $("#codebookImportModal #displayImportCodebookDataButton").click();
        }
    });
}

function generateCodebookFilter(tableDataNames, getImportCodebookItemsUrl, userLocalization, localization, beforeDataSend, additionalFilters, onLoad) {
    let $filters = $("<div class='row codebook-filters'></div>");

    if (additionalFilters) {
        $filters.append("<div class='col-xs-12'><div class='row'>" + additionalFilters + "</div></div>");
    }

    $filters.append("<div class='col-sm-5 m-t-xs'><label>" + localization.importType + "</label><select class='form-control codebook-importType' style='width:auto; display:inline-block'><option value='0'>" + localization.importTypeAdding + "</option><option value='1'>" + localization.importTypeAddEdit + "</option></select></div>");

    $filters.append("<div class='col-sm-4 m-t-xs'><label>" + localization.forCountry + "</label><select class='form-control codebook-forcountry' style='width:auto; display:inline-block'></select></div>");

    $downloadFromServerButton = $("<button class='btn btn-primary pull-right m-b-xs' id='displayImportCodebookDataButton'><i class='fa fa-arrow-right'></i> " + localization.dowloadFromServer + "</button>");
    $downloadFromServerButtonContainer = $("<div class='col-sm-3 m-t-xs'></div>");

    $downloadFromServerButtonContainer.append($downloadFromServerButton);
    $filters.append($downloadFromServerButtonContainer);

    $downloadFromServerButton.on("click", function () {
        displayImportCodebookData(this, "codebookImportModal", getImportCodebookItemsUrl, tableDataNames, beforeDataSend, userLocalization, onLoad);
    });

    return $filters;
}

function generateCodebookTable(tableTitles, localization) {
    let codebookTable = "<div style='width:100%;overflow:auto;'><table class='table table-bordered add-modal-table'><thead><tr><th width='50px'>" + localization.yesNo + "</th>";
    for (let a = 0; a < tableTitles.length; a++) {
        codebookTable += "<th>" + tableTitles[a] + "</th>";
    }
    codebookTable += "</tr></thead><tbody></tbody></table></div>";

    return codebookTable;
}

function generateCodebookTableDataRow(tableDataNames, data) {
    let row = "<tr data='" + JSON.stringify(data) + "'><td style='text-align:center;padding-top: 3px;'><input type='checkbox' class='custom-checkbox codebook-checkbox' " + (data.Marked ? "checked" : "") + "></td>";
    for (let a = 0; a < tableDataNames.length; a++) {
        row += "<td style='vertical-align: middle;padding: 0px 8px'>" + (data[tableDataNames[a]] ? data[tableDataNames[a]] : "") + "</td>";
    }
    row += "</tr>";

    return row;
}

async function getImportCodebookData(element, url, userLocalization, onLoad) {
    let codebookData;
    $(element).find("i").addClass("fa-spinner fa-spin");
    $(element).prop("disabled", true);
    $(element).closest(".custom-modal-content").find(".codebook-forcountry").prop("disabled", true);

    await fetch(url, {
        method: "GET",
        headers: { 'Content-Type': 'application/json' }
    }).then((response) => response.json()
    ).then(async (importData) => {
        if (!importData) throw "Error";

        let localizationFilters = [{ Localization: "SI" }, { Localization: "RS" }, { Localization: "MK" }, { Localization: "HR" }, { Localization: "EU" }];

        if (importData.Dataset) {
            codebookData = importData.Dataset;
            if (importData.Localization && importData.Localization.length > 0) {
                localizationFilters = importData.Localization;
            }
        }
        else {
            codebookData = importData;
        }

        let $localizationSelect = $(element).closest(".custom-modal-content").find(".codebook-forcountry");
        if ($localizationSelect.find("option").length < 1) {
            $localizationSelect.empty();
            for (let i = 0; i < localizationFilters.length; i++) {
                let localization = localizationFilters[i];
                $localizationSelect.append("<option value='" + localization.Localization + "'>" + localization.Localization + "</option>");
            }
            $localizationSelect.val(userLocalization);
        }

        if (onLoad) onLoad(importData);

        $(element).closest(".custom-modal-content").find(".codebook-forcountry").prop("disabled", false);

        $(element).find("i").removeClass("fa-spinner fa-spin");
        $(element).prop("disabled", false);
    }).catch(async (error) => {
        $(element).closest(".custom-modal-content").find(".codebook-forcountry").prop("disabled", false);
        $().customModal({
            destroyOnClose: true,
            showCloseButton: true,
            closeOtherModals: false,
            type: "error",
            text: $("#GeneralErrorMessage").val(),
            buttons: [
                {
                    icon: 'fa fa-check',
                    text: $("#ConfirmLoc").val(),
                    closeOnAction: true,
                    type: 'primary'
                }
            ]
        });
        $(element).find("i").removeClass("fa-spinner fa-spin");
        $(element).prop("disabled", false);
    });

    return codebookData;
}

async function displayImportCodebookData(element, modalId, url, tableDataNames, beforeDataSend, userLocalization, onLoad) {
    let $modal = $("#" + modalId);

    let jsonData = {
        inputType: $modal.find(".codebook-importType").val(),
        localization: $modal.find(".codebook-forcountry").val() === null ? userLocalization : $modal.find(".codebook-forcountry").val()
    };
    if (beforeDataSend) beforeDataSend(jsonData);

    let getImportCodebookDataUrl = url + "?";
    const keys = Object.keys(jsonData);
    for (const key of keys) {
        if (jsonData[key]) getImportCodebookDataUrl += `${key}=${jsonData[key]}&`;
    }

    let codebookData = await getImportCodebookData(element, getImportCodebookDataUrl, userLocalization, onLoad);
    if (!codebookData || !tableDataNames) return;

    let codebookRows = "";
    for (let a = 0; a < codebookData.length; a++) {
        codebookRows += generateCodebookTableDataRow(tableDataNames, codebookData[a]);
    }

    $("#" + modalId).find("table tbody").empty().append(codebookRows);
    $("#" + modalId + " .custom-checkbox").customCheckbox();
}

async function importCodebook(modalId, url, onSuccess, beforeDataSend) {
    let $modal = $("#" + modalId);
    let $dataElements = $modal.find("table tbody tr");
    let data = [];

    for (let a = 0; a < $dataElements.length; a++) {
        let $element = $($dataElements[a]);
        let elementData = JSON.parse($element.attr("data"));
        elementData.Marked = $element.find(".codebook-checkbox").is(":checked");
        data.push(elementData);
    }

    if (!data || data.length < 1) return;

    let jsonData = {
        codebookItems: data,
        inputType: $modal.find(".codebook-importType").val(),
        localization: $modal.find(".codebook-forcountry").val()
    };

    if (beforeDataSend) beforeDataSend(jsonData);

    await fetch(url, {
        method: "POST",
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(jsonData)
    }).then((response) => response.json()
    ).then(async (success) => {
        if (!success) throw "Error";

        if (onSuccess) onSuccess();
    }).catch(async (error) => {
        $().customModal({
            destroyOnClose: true,
            showCloseButton: true,
            closeOtherModals: false,
            type: "error",
            text: $("#GeneralErrorMessage").val(),
            buttons: [
                {
                    icon: 'fa fa-check',
                    text: $("#ConfirmLoc").val(),
                    closeOnAction: true,
                    type: 'primary'
                }
            ]
        });
    });
}