this.Praesentation = this.Praesentation || {};
this.Praesentation.Path = this.Praesentation.Path || {};
this.Praesentation.Api = this.Praesentation.Api || {};
this.Praesentation.Vue = this.Praesentation.Vue || {};
this.Praesentation.Vue.Methods = this.Praesentation.Vue.Methods || {};

this.Praesentation.log = function(obj) {
    if (Praesentation.Api.Config.activate_log) {
        if (obj.title && obj.details) {
            var entry = $('<div>');
            entry.append($('<span class="fw-bold pe-2">').html(obj.title))
            entry.append($('<span class="fw-light">').html(obj.details))
            $('#log_entries').append(entry);
        } else {
            $('#log_entries').append(obj);
        }
    } else {
        console.log(obj);
    }
    return obj;
}



this.Praesentation.handleLoggingMode = function() {
    if (!Praesentation.Api.Config.activate_log) {
        return;
    }

    var div = $('<div style="margin-bottom:70px;display:none" class="container border p-4 logging-element">');
    $('body').append(div);
    div.append($('<h5>').append("LoggingModus ").append($('<small>').append('ist aktiviert')));
    div.append($('<code>').append($('<div id="log_entries">')));

    $.each(Praesentation.Api.Config.log, function(index, element) {
        Praesentation.log(element);
    });

}

this.Praesentation.error = function(obj) {
    Praesentation.log({
        title: "Fehler:",
        details: obj
    });
    alert(obj);
}

this.Praesentation.Api.Config = [];
this.Praesentation.Api.Termin = [];


//Nicht bei jeder Seite gefüllt
this.Praesentation.Api.Wahl;
this.Praesentation.Api.Ergebnis;

this.Praesentation.goTo = function(baseUrl, params) {


    const ret = [];
    for (var d in params)
        ret.push(encodeURIComponent(d) + '=' + encodeURIComponent(params[d]));
    var url = baseUrl + "?" + ret.join('&');

    alert("Achtung Abbruch! Hier wird noch die alte Linkart aufgerufen: " + url);

    // window.location.href = url;
}

this.Praesentation.link = function(link, params) {
    window.location.href = Praesentation.formatURLfromLink(link, params);
}


this.Praesentation.extractTemplateTypeFromUrl = function() {
    var aktuelles_template = window.location.pathname.split("/")[
    window.location.pathname.split("/").length - 1
        ];

    aktuelles_template = aktuelles_template.split(".")[
    aktuelles_template.split(".").length - 2
        ];

    return aktuelles_template;
}

this.Praesentation.formatURLfromLink = function(link, params) {

    var LINK_TYPE_EXTERNEL_KEY = 'external';


    if (!link) {
        console.log("formatURLfromLink: Link wurde nicht mit übergeben. Hier die params: ", params);
    }

    if (!link.type) {
        alert("Praesentation.link: Achtung der Link hat keinen -type-!");
    }

    var url = link.type;
    switch (link.type) {
        case 'uebersicht':
            url = 'uebersicht.html';
            break;
        case 'ergebnis':
            url = 'ergebnis.html';
            break;
        case 'hochrechnung':
            url = 'hochrechnung.html';
            break;
        case 'guv':
            url = 'guv.html';
            break;
        case 'ergebnisgrafik':
            url = 'ergebnisgrafik.html';
            break;
        case LINK_TYPE_EXTERNEL_KEY:
            url = link.url;
            break;
        case 'geografik':
            url = 'geografik.html';
            break;
        default:
            Praesentation.error("Linktype unbekannt: " + link.type);
            break;
    }


    const ret = [];

    if (link.type != LINK_TYPE_EXTERNEL_KEY) {
        if (link.id) {
            params.id = link.id;
        }

        for (var d in params)
            ret.push(encodeURIComponent(d) + '=' + encodeURIComponent(params[d]));

        url += "?" + ret.join('&');
    }
    return url;
}

this.Praesentation.UrlSearchParams = function() {
    var query = window.location.search.substring(1);

    var vars = query.split("&");
    var query_string = {};
    for (var i = 0; i < vars.length; i++) {
        var pair = vars[i].split("=");
        var key = decodeURIComponent(pair[0]);
        var value = decodeURIComponent(pair[1]);
        // If first entry with this name
        if (typeof query_string[key] === "undefined") {
            query_string[key] = decodeURIComponent(value);
            // If second entry with this name
        } else if (typeof query_string[key] === "string") {
            var arr = [query_string[key], decodeURIComponent(value)];
            query_string[key] = arr;
            // If third or later entry with this name
        } else {
            query_string[key].push(decodeURIComponent(value));
        }
    }
    return query_string;
}

this.Praesentation.readCookie = function(cname) {
    var name = cname + "=";
    var decodedCookie = decodeURIComponent(document.cookie);
    var ca = decodedCookie.split(';');
    for (var i = 0; i < ca.length; i++) {
        var c = ca[i];
        while (c.charAt(0) == ' ') {
            c = c.substring(1);
        }
        if (c.indexOf(name) == 0) {
            return c.substring(name.length, c.length);
        }
    }
    return "";
}

this.Praesentation.Path.toGeoGrafikJson = function(wahl_id, id, stimmentyp) {
    var Path = "../daten/api/wahl_" + wahl_id + "/";
    return Path + "geografik_" + id + ".json?ts=" + Date.now();
}

this.Praesentation.Path.toGeoGrafikFeatureJson = function(wahl_id, id, stimmentyp) {
    var Path = "../daten/api/wahl_" + wahl_id + "/";
    return Path + "geografik_features_" + id + "_" + stimmentyp + ".json?ts=" + Date.now();
}

this.Praesentation.Path.ToErgebnisJson = function(wahl_id, id, stimmentyp) {
    var Path = "../daten/api/wahl_" + wahl_id + "/";
    return Path + "ergebnis_" + id + "_" + stimmentyp + ".json?ts=" + Date.now();
}

this.Praesentation.Path.ToWahlJson = function() {
    var Path = "../daten/api/wahl_" + Praesentation.UrlSearchParams().wahl_id + "/";
    return Path + "wahl.json?ts=" + Date.now();
}

this.Praesentation.Path.ToConfigJson = function() {
    return "../daten/api/config.json";
}

this.Praesentation.Path.ToTerminJson = function() {
    return "../daten/api/termin.json";
}

this.Praesentation.Path.ToNewsboxJson = function() {
    return "../daten/api/newsbox.json";
}

this.Praesentation.Path.ToNeusteErgebnisseJson = function() {
    return "../daten/api/neuste_ergebnisse.json?ts=" + Date.now();
}

this.Praesentation.Path.ToWahlraeumeUebersichtJson = function() {
    return "../daten/api/wahlraeume_uebersicht.json";
}

this.Praesentation.Path.ToStrassenJson = function() {
    return "../daten/api/strassen.json";
}

this.Praesentation.Path.ToHochrechnungJson = function() {
    var Path = "../daten/api/wahl_" + Praesentation.UrlSearchParams().wahl_id + "/";
    return Path + "hochrechnung.json?ts=" + Date.now();
}

this.Praesentation.Path.ToEigeneSeitenJson = function() {
    return "../daten/api/eigene_seiten.json";
}

this.Praesentation.Path.ToUebersichtJson = function() {
    var wahl_id = Praesentation.UrlSearchParams().wahl_id;
    var id = Praesentation.UrlSearchParams().id;
    var stimmentyp = Praesentation.UrlSearchParams().stimmentyp;

    var Path = "../daten/api/wahl_" + wahl_id + "/";

    return Path + "uebersicht_" + id + "_" + stimmentyp + ".json?ts=" + Date.now();
}

this.Praesentation.Path.ToWahlraeumeJson = function() {
    var wahlraum_id = Praesentation.UrlSearchParams().bezirk_id;
    return "../daten/api/wahlraum_" + wahlraum_id + ".json";
}

this.Praesentation.Path.ToOpenDataJson = function() {
    return "../daten/opendata/open_data.json";
}

/**
 * Initialisiert die App mit allen nötigen JSON's (falls vorhanden auch die Wahl.json).
 * Anschließend wird die übergebene function ausgeführt.
 */
this.Praesentation.initApp = function(readyFunction) {


    $.getJSON(Praesentation.Path.ToConfigJson(), function(data) {
        Praesentation.Api.Config = data;

        //Print File-Infos 'VOT-19253
        Praesentation.log("config: " + JSON.stringify({
            file_version: data.file_version,
            file_timestamp: data.file_timestamp,
            url: Praesentation.Path.ToConfigJson()
        }));

        Praesentation.handleLoggingMode();

        //Zählpixel
        if (Praesentation.Api.Config.eigene_texte && Praesentation.Api.Config.eigene_texte.zaehlpixel) {
            $(document.body).append(Praesentation.Api.Config.eigene_texte.zaehlpixel);
        }

        $.getJSON(Praesentation.Path.ToTerminJson(), function(data) {
            Praesentation.Api.Termin = data;

            //Print File-Infos 'VOT-19253
            Praesentation.log("termin: " + JSON.stringify({
                file_version: data.file_version,
                file_timestamp: data.file_timestamp,
                url: Praesentation.Path.ToTerminJson()
            }));

            if (Praesentation.UrlSearchParams().wahl_id) {

                $.getJSON(Praesentation.Path.ToWahlJson(), function(data) {
                    Praesentation.Api.Wahl = data;

                    //Print File-Infos 'VOT-19253
                    Praesentation.log("wahl: " + JSON.stringify({
                        file_version: data.file_version,
                        file_timestamp: data.file_timestamp,
                        url: Praesentation.Path.ToWahlJson()
                    }));

                    readyFunction();

                    //Jetzt zeige alles an!
                    $(document.body).slideDown(500);
                });

            } else {
                readyFunction();

                //Jetzt zeige alles an!
                $(document.body).slideDown(500);
            }

        });
    });

}

this.Praesentation.ladeErgebnis = function(readyFunction, webInitFunction) {
    var wahl_id = Praesentation.UrlSearchParams().wahl_id;
    var id = Praesentation.UrlSearchParams().id;
    var stimmentyp = Praesentation.UrlSearchParams().stimmentyp;

    $.getJSON(Praesentation.Path.ToErgebnisJson(wahl_id, id, stimmentyp), function(data) {
        Praesentation.Api.Ergebnis = data;

        //Print File-Infos 'VOT-19253
        Praesentation.log("ergebnis: " + JSON.stringify({
            file_version: data.file_version,
            file_timestamp: data.file_timestamp,
            url: Praesentation.Path.ToErgebnisJson(wahl_id, id, stimmentyp)
        }));

        if (Praesentation.Api.Ergebnis.Komponente) {
            readyFunction();
        } else {
            webInitFunction();
        }

    }).fail(function() {
        alert("Fehler 404: Die Datei wurde nicht gefunden. (" + Praesentation.Path.ToErgebnisJson(wahl_id, id, stimmentyp) + ")");
    });

}


this.Praesentation.ladeUebersicht = function(readyFunction, webInitFunction) {
    $.getJSON(Praesentation.Path.ToUebersichtJson(), function(data) {

        //Print File-Infos 'VOT-19253
        Praesentation.log("uebersicht: " + JSON.stringify({
            file_version: data.file_version,
            file_timestamp: data.file_timestamp,
            url: Praesentation.Path.ToUebersichtJson()
        }));

        if (data && data.tabelle) {
            readyFunction(data);
        } else {
            webInitFunction();
        }
    }).fail(function() {
        webInitFunction();
    });
}

this.Praesentation.ladeWahlraum = function(readyFunction) {
    $.getJSON(Praesentation.Path.ToWahlraeumeJson(), function(data) {

        //Print File-Infos 'VOT-19253
        Praesentation.log("wahlraum: " + JSON.stringify({
            file_version: data.file_version,
            file_timestamp: data.file_timestamp,
            url: Praesentation.Path.ToWahlraeumeJson()
        }));

        readyFunction(data);
    });
}

/**
 * Lädt die erforderlichen Komponenten (Footer) sowie die übergebenen Komponenten. ACHTUNG: Hierbei ist die Bezeichnung der Komponenten zwingend vorgegeben:
 * <komponente_#NAME#></komponente_#NAME#> erwarte eine Datei im Komponenten Verzeichnis mit dem Namen: #NAME#.vue
 *
 * Erwartet wird ein Array von Strings
 */
this.Praesentation.Vue.ladeKomponenten = function(komponenten) {

    var components = {};
    components.komponente_footer = httpVueLoader('komponenten/footer.vue');

    for (i = 0; i < komponenten.length; i++) {
        components['komponente_' + komponenten[i]] = httpVueLoader('komponenten/' + komponenten[i] + '.vue');
    }

    return components;
}

this.Praesentation.Vue.Methods.navigate = function(event) {
    event.preventDefault();

    var UrlSearchParams = Praesentation.UrlSearchParams();

    var link = event.target;

    alert("Achtung: Diese Art der Verlinkung wird nicht mehr unterstützt! (Praesentation.Vue.Methods.navigate)")

    Praesentation.goTo(link.getAttribute("href"), {
        "wahl_id": UrlSearchParams.wahl_id,
        "stimmentyp": UrlSearchParams.stimmentyp,
        "ebene": UrlSearchParams.ebene,
        "gebiet_id": UrlSearchParams.gebiet_id
    })
}

this.Praesentation.Datatables2GermanLanguage = {
    "sEmptyTable": "Keine Daten in der Tabelle vorhanden",
    "sInfo": "_START_ bis _END_ von _TOTAL_ Einträgen",
    "sInfoEmpty": "0 bis 0 von 0 Einträgen",
    "sInfoFiltered": "(gefiltert von _MAX_ Einträgen)",
    "sInfoPostFix": "",
    "sInfoThousands": ".",
    "sLengthMenu": "_MENU_ Einträge anzeigen",
    "sLoadingRecords": "Wird geladen...",
    "sProcessing": "Bitte warten...",
    "sSearch": "Suchen",
    "sZeroRecords": "Keine Einträge vorhanden.",
    "oPaginate": {
        "sFirst": "Erste",
        "sPrevious": "Zurück",
        "sNext": "Nächste",
        "sLast": "Letzte"
    },
    "oAria": {
        "sSortAscending": ": aktivieren, um Spalte aufsteigend zu sortieren",
        "sSortDescending": ": aktivieren, um Spalte absteigend zu sortieren"
    }
};