/// <reference path="../../node_modules/@types/jquery/index.d.ts" />
/// <reference path="../../node_modules/@types/jquery.validation/index.d.ts" />
/// <reference path="../../node_modules/@types/jquery-validation-unobtrusive/index.d.ts" />
/// <reference path="../../node_modules/sweetalert2/sweetalert2.d.ts" />
/// <reference path="./jquery-extensions.d.ts" />
// Der Haupteinstiegspunkt für JS. Included diverse andere JS, falls benötigt.
// --
//import $ from "jquery";
//// Erweiterung der jQuery-Schnittstelle
//declare global {
//    interface JQuery {
//        loadExtended(
//            url: string,
//            data?: any,
//            callback?: (response: string, status: string, xhr: JQuery.jqXHR<any>) => void
//        ): JQuery;
//    }
//}
// Definition der `loadExtended`-Methode.
// Eine erweiterte Version der `$.load()`-Methode, die zusätzliche Logik hinzufügt.
// Hier auch automatisch den Code aufrufen, der das eingefügte HTML verarbeitet.
$.fn.loadExtended = function (url, data, callback) {
    // Rufe die originale `.load()`-Methode auf
    return this.load(url, data, function (response, status, xhr) {
        if (status == "error") {
            App.handleErrorXHR(xhr);
        }
        //// Zusätzliche Logik hinzufügen
        //console.log("Extended logic: Content loaded from", url);
        //// Beispiel: Logging der geladenen Inhalte
        //console.log("Response Content:", response);
        // Nach dem Laden der Inhalte die Form-Gruppen im Container rendern.
        App.renderFormGroupsInContainer($(this));
        // Rufe das Callback der ursprünglichen `load()`-Methode auf (falls vorhanden)
        if (callback) {
            callback(response, status, xhr);
        }
    });
};
// --
//interface JQuery {
//    // https://stackoverflow.com/questions/35071120/property-valhooks-does-not-exist-on-type-jquerystatic/35071204
//    popover: any;
//}
var dummy;
var Swal;
var DevExpress;
var toastr;
var loadingPanelClosed = true;
class StringHelper {
    static IsNullOrEmpty(s) {
        return typeof s === "undefined" || s == null || s === "";
    }
}
class App {
    // Zentrale Stelle um Fehler zu behandeln.
    static HandleAjaxBeginFormFailure(xhr, status, thrownError) {
        if (xhr.status === 0) {
            console.log(thrownError);
            return;
        }
        if (xhr.status === 401) {
            // https://sweetalert2.github.io/#configuration
            Swal.fire({
                title: "Anmeldung abgelaufen",
                text: "Bitte melden Sie sich erneut an.",
                icon: "warning"
            }).then(() => {
                location.reload();
            });
        }
        else if (xhr.status === 404) {
            // https://sweetalert2.github.io/#configuration
            Swal.fire("Seite nicht gefunden", "Die Angeforderte Seite konnte nicht gefunden werden.", "error");
        }
        else {
            let error = thrownError;
            if (xhr.responseText) {
                error += " " + xhr.responseText;
            }
            // https://sweetalert2.github.io/#configuration
            Swal.fire("Fehler", `Error - ${xhr.status}: ${error}`, "error");
            console.log(`Error - ${xhr.status}: ${thrownError}`);
            console.log(xhr);
            console.log(status);
            console.log(thrownError);
        }
    }
    static handleError(message, wantToast = false) {
        ClientLogging.Log(LogType.Error, message);
        if (StringHelper.IsNullOrEmpty(message))
            message = "Ein Fehler ist aufgetreten.";
        if (!StringHelper.IsNullOrEmpty(message)) {
            if (wantToast) {
                // https://github.com/CodeSeven/toastr
                toastr.error(message);
            }
            else {
                // https://sweetalert2.github.io/#configuration
                Swal.fire({
                    title: "Etwas ist schief gelaufen",
                    text: message,
                    showCancelButton: true,
                    cancelButtonText: "Schließen",
                    focusCancel: true,
                    showConfirmButton: false,
                    heightAuto: false,
                    allowEscapeKey: true,
                    allowEnterKey: true
                });
            }
        }
    }
    static getXHRErrorMessage(xhr) {
        let errorMessage = xhr.getResponseHeader("errorMessage");
        if (errorMessage) {
            return errorMessage;
        }
        else if (!StringHelper.IsNullOrEmpty(xhr.responseText)) {
            return xhr.responseText;
        }
        else {
            return `${xhr.status} ${xhr.statusText}`;
        }
    }
    static handleErrorXHR(xhr, wantToast = false) {
        const errorMessage = xhr.getResponseHeader("errorMessage");
        if (errorMessage) {
            App.handleError(errorMessage, wantToast);
        }
        else if (!StringHelper.IsNullOrEmpty(xhr.responseText)) {
            App.handleError(xhr.responseText, wantToast);
        }
        else {
            App.handleError(`${xhr.status} ${xhr.statusText}`, wantToast);
        }
    }
    static handleSuccess(response) {
        if (!StringHelper.IsNullOrEmpty(response)) {
            // https://github.com/CodeSeven/toastr
            toastr.success(response);
        }
        /*
        const contentWidth = $("#content").width();
        const notifyWidth = contentWidth > 992 ? contentWidth * 0.5 : contentWidth;

        DevExpress.ui.notify(
            {
                message: response.message,
                position: { at: 'center top', offset: '0 110' },
                width: notifyWidth
            },
            response.result,
            response.displayTime ? response.displayTime : 1000);
        */
    }
    static showLoadingPanelSimple(text = null) {
        App.showLoadingPanel(null, 1, text);
    }
    static showLoadingPanel($container = null, delay = 500, text = null) {
        loadingPanelClosed = false;
        setTimeout(() => {
            if (!loadingPanelClosed) {
                const $loadingPanel = $("#loading-panel");
                if ($container) {
                    const pos = $container.position() || { top: 0, left: 0 };
                    let height = $container.outerHeight(true);
                    if (height === 0) {
                        $container.css("min-height", "150px");
                        height = 150;
                    }
                    $loadingPanel.css("position", "absolute");
                    $loadingPanel.css("top", pos.top + "px");
                    $loadingPanel.css("left", pos.left + "px");
                    $loadingPanel.width($container.outerWidth(true));
                    $loadingPanel.height(height);
                }
                else {
                    // https://jsfiddle.net/TtL7R/1/
                    $loadingPanel.css("position", "fixed");
                    $loadingPanel.css("top", "0px");
                    $loadingPanel.css("left", "0px");
                    $loadingPanel.width("100%");
                    $loadingPanel.height("100%");
                }
                const $lpt = $("#loading-panel-text");
                if (text) {
                    // Setzen.
                    $lpt.text(text);
                }
                else {
                    // Zurücksetzen, falls zuvor geändert wurde.
                    $lpt.text($lpt.data("default-text"));
                }
                $loadingPanel.addClass("show");
            }
        }, delay);
    }
    static hideLoadingPanel() {
        loadingPanelClosed = true;
        const $loadingPanel = $("#loading-panel");
        $loadingPanel.removeClass("show");
        $loadingPanel.css("top", 0);
        $loadingPanel.css("left", 0);
        $loadingPanel.width(0);
        $loadingPanel.height(0);
    }
    static sleep(milliseconds) {
        const now = new Date().getTime();
        while (new Date().getTime() < now + milliseconds) {
            /* Do nothing */
        }
    }
    /**
     * Format bytes as human-readable text.
     *
     * @param bytes Number of bytes.
     * @param si True to use metric (SI) units, aka powers of 1000. False to use
     *           binary (IEC), aka powers of 1024.
     * @param dp Number of decimal places to display.
     *
     * @return Formatted string.
     */
    static humanFileSize(bytes, si = false, dp = 1) {
        // https://stackoverflow.com/a/14919494/107625
        const thresh = si ? 1000 : 1024;
        if (Math.abs(bytes) < thresh) {
            return `${bytes} B`;
        }
        const units = si
            ? ["kB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB"]
            : ["KiB", "MiB", "GiB", "TiB", "PiB", "EiB", "ZiB", "YiB"];
        let u = -1;
        const r = 10 ** dp;
        do {
            bytes /= thresh;
            ++u;
        } while (Math.round(Math.abs(bytes) * r) / r >= thresh && u < units.length - 1);
        // https://stackoverflow.com/a/39686116/107625
        const num = bytes.toLocaleString(undefined, // TODO: Language-Code.
        {
            minimumFractionDigits: dp,
            maximumFractionDigits: dp
        });
        //const num = bytes.toFixed(dp);
        return `${num} ${units[u]}`;
    }
    /**
     * Füllt ein per dynamischem AJAX-Aufruf zurück geliefertes HTML (in der Regel von einem
     * dynamisch gerenderten Partial) in einen DOM-Container.
     */
    static fillHtmlIntoContainer(html, $container) {
        $container.html(html);
        App.renderFormGroupsInContainer($container);
    }
    /**
     * Diese Funktion sollte nach jedem Ajax-GET-Callback ausgeführt werden.
     * u. a. wird die Client-Validierung aktiviert, sowie die Inline-Labels.
     */
    static renderFormGroupsInContainer($container) {
        // Code hier aus "km.forms.js", Funktion "renderFormGroupsInContainer" übernommen.
        // TODO: Später ggf. noch mehr Code von dort übernehmen.
        //Client-Validation
        if ($.validator !== undefined && $.validator.unobtrusive !== undefined) {
            $.validator.unobtrusive.parse($container);
        }
        //Bootstrap - Popover initialisieren
        const p = $("[data-toggle='popover']");
        p.popover();
    }
}
var LogType;
(function (LogType) {
    LogType[LogType["Error"] = 0] = "Error";
    LogType[LogType["Info"] = 1] = "Info";
    LogType[LogType["Warning"] = 2] = "Warning";
})(LogType || (LogType = {}));
class ClientLogging {
    static Url;
    static Log(type, message) {
        if (!message || typeof message === "undefined")
            message = "";
        if (message !== "") {
            switch (type) {
                case LogType.Error:
                    console.error(message);
                    break;
                case LogType.Info:
                    console.log(message);
                    break;
                case LogType.Warning:
                    console.warn(message);
                    break;
                default:
                    console.log(message);
                    break;
            }
        }
        if (this.Url && typeof this.Url !== "undefined") {
            $.ajax({
                url: this.Url.replace("_type_", type).replace("_message_", message),
                method: "POST",
                success: (data) => {
                    this.handleFurtherAction(data.action);
                }
            });
        }
    }
    static handleFurtherAction(action) {
    }
}
class ValidationSummary {
    /**
     * Löscht alle Validierungen in einem Form.
     * Siehe https://stackoverflow.com/a/14831537/107625
     */
    static clearAllFormValidationErrors(formId) {
        // get the form inside we are working - change selector to your form as needed
        var $form = $(`#${formId}`);
        // get validator object
        var $validator = $form.validate();
        // get errors that were created using jQuery.validate.unobtrusive
        var $errors = $form.find(".field-validation-error span");
        // trick unobtrusive to think the elements were succesfully validated
        // this removes the validation messages
        $errors.each(function () {
            var t = $(this);
            var f = $validator.settings.success;
            f(t);
        });
        // clear errors from validation
        $validator.resetForm();
    }
    static clearValidationErrors(summaryElementId) {
        const container = $(`#${summaryElementId}`);
        const list = container.find("ul");
        container.addClass("validation-summary-valid").removeClass("validation-summary-errors");
        list.empty();
    }
    static addValidationError(message, summaryElementId) {
        const container = $(`#${summaryElementId}`);
        const list = container.find("ul");
        container.addClass("validation-summary-errors").removeClass("validation-summary-valid");
        $("<li />").html(message).appendTo(list);
    }
}
