async function openImportCodebookModal(title, tableTitles, tableDataNames, getImportMailboxesUrl, importMailboxesUrl, helpUrl, localization, userLocalization, onSuccess) {
    let codebookModalFilters = generateCodebookFilter(tableDataNames, getImportMailboxesUrl, userLocalization, localization);
    let codebookTable = generateCodebookTable(tableTitles, localization);

    let codebookModalBody = "<div style='overflow-x: hidden;'>" + codebookModalFilters + codebookTable + "</div>";

    $().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", importMailboxesUrl, onSuccess); }
            }
        ]
    });
}

function generateCodebookFilter(tableDataNames, getImportMailboxesUrl, userLocalization, localization) {
    let filters = "<div class='row codebook-filters'>";

    filters += "<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>";

    let countryFilters = ["SI", "RS", "EU", "HR"];
    let countrySelectOptions = "";
    for (let a = 0; a < countryFilters.length; a++) {
        countrySelectOptions += "<option value='" + countryFilters[a] + "' " + (countryFilters[a] === userLocalization ? "selected" : "") + ">" + countryFilters[a] + "</option>";
    }
    filters += "<div class='col-sm-4 m-t-xs'><label>" + localization.forCountry + "</label><select class='form-control codebook-forcountry' style='width:auto; display:inline-block'>" + countrySelectOptions + "</select></div>";

    filters += "<div class='col-sm-3 m-t-xs'><button class='btn btn-primary pull-right m-b-xs' onClick='displayImportCodebookData(this, \"codebookImportModal\", \"" + getImportMailboxesUrl + "\", " + JSON.stringify(tableDataNames) + ")'><i class='fa fa-arrow-right'></i> " + localization.dowloadFromServer + "</button></div>";

    filters += "</div>";

    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) {
    let codebookData;
    $(element).find("i").addClass("fa-spinner fa-spin");
    $(element).prop("disabled", true);

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

        codebookData = importData;

        $(element).find("i").removeClass("fa-spinner fa-spin");
        $(element).prop("disabled", false);
    }).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'
                }
            ]
        });
        $(element).find("i").removeClass("fa-spinner fa-spin");
        $(element).prop("disabled", false);
    });

    return codebookData;
}

async function displayImportCodebookData(element, modalId, url, tableDataNames) {
    let $modal = $("#" + modalId);
    let codebookData = await getImportCodebookData(element, url + "?inputType=" + $modal.find(".codebook-importType").val() + "&localization=" + $modal.find(".codebook-forcountry").val());
    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) {
    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;

    await fetch(url, {
        method: "POST",
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
            mailboxes: data,
            inputType: $modal.find(".codebook-importType").val(),
            localization: $modal.find(".codebook-forcountry").val()
        })
    }).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'
                }
            ]
        });
    });
}