let tableData_global; // fetched date
let range_global = null;
let filterId_global = null;
let propertyToShowMap_global = {};
let properties_global;
// true/false-map für properties


const doFetchCountries = (filterId, range) => {
    let url_append = "";
    if (filterId !== null && filterId !== undefined) {
        url_append += "/" + filterId;
    }
    if (range !== null && range !== undefined) {
        url_append += "/" + range;
    }

    $.ajax({url: "/items" + url_append}).done((data) => {
        if (data instanceof Array) tableData_global = data;
        else {
            tableData_global = [];
            tableData_global.push(data);
        }
        doTablePrint();
    });
};

const onLoadedProperties = (props) => {
    properties_global = props;
    properties_global.forEach(function (prop) {
        propertyToShowMap_global[prop] = true;
    });
    // standardmäßig alle properties anzeigen; map aufbauen

    // options im select
    let html1 = "";
    properties_global.forEach(function (prop) {
        html1 += "<option value=\"" + prop + "\">" + prop + "</option>"
    });
    $("#prop_selection").html(html1);
};

const doTablePrint = () => {
    // thead
    let html = "";
    properties_global.forEach((prop) => {
        if (propertyToShowMap_global[prop]) {
            html += "<th>" + prop + "</th>";
        }
    });
    $("#table_head").html(html);
    // tbody
    html = "";
    tableData_global.forEach(row => {
        html += "<tr>";
        properties_global.forEach((key) => {
            if (propertyToShowMap_global[key]) {
                html += "<td>" + row[key] + "</td>";
            }
        });
        html += "</tr>";
    });
    $("#table_body").html(html);
};

const clickListenersInit = () => {

    $("#country_filter_submit").click(() => {
        // Filterung
        filterId_global = $("#country_filter_id").val();
        range_global = $("#country_filter_range").val();
        if (range_global === "") {
            doFetchCountries(filterId_global, null);
        } else {
            doFetchCountries(filterId_global, range_global);
        }
    });


    $("#rm_submit").click(() => {     // Löschen
        $.ajax({
            url: '/items/' + $("#country_delete_id").val(), type: 'DELETE'
        }).done(() => {
            console.log("Item mit ID " + $("#country_delete_id").val() + " gelöscht!");
        });
        doFetchCountries(filterId_global, range_global);
    });

    $("#add_submit").click(() => {
        $.ajax({
            url: "/items",
            type: "POST",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            data: JSON.stringify({
                name: $("#country_name").val(),
                "birth_rate_per_1000": $("#country_birth").val(),
                "cell_phones_per_100": $("#country_cellphone").val()
            })
        }).done(function () {
            console.log("Item angelegt!");
        });
        doFetchCountries(filterId_global, range_global);
    });
    $("#show_selected_prop").click(() => {
        propertyToShowMap_global[$("#prop_selection option:selected").text()] = true;
        doTablePrint();
    });


    $("#hide_selected_prop").click(() => {
        propertyToShowMap_global[$("#prop_selection option:selected").text()] = false;
        doTablePrint();
    });
};


window.onload = () => {
    clickListenersInit();
    $.ajax({url: "/properties"}).done((data) => {
        onLoadedProperties(data);
        doFetchCountries(null, null);
    });
};
