/* global Bdf,Overlay,URLSearchParams,$$ */

Bdf.Multi = {};

Bdf.Multi.ping = function (requestParameters, pingCallback) {
    var ajaxData = {};
    if (requestParameters) {
        Object.assign(ajaxData, requestParameters);
    }
    ajaxData.json = "ping";
    $.ajax({
        url: Bdf.URL + "multi-admin",
        method: "GET",
        dataType: "json",
        data: ajaxData,
        xhrFields: {
           withCredentials: true
        },
        success: function (data, textStatus) {
            if (pingCallback) {
                pingCallback(data);
            }
        }
    });
};

Bdf.Multi.checkAuthentification = function (callback) {
    Bdf.Multi.ping({}, function (data) {
        if (!data.authentified) {
            Bdf.Multi.showAuthentificationOverlay(callback);
        } else {
            callback();
        }
     });
};

Bdf.Multi.showAuthentificationOverlay = function (callback) {
    var defaultLogin = "";
    if (URLSearchParams) {
        var searchParams = new URLSearchParams(window.location.search);
        if (searchParams.has("login")) {
            defaultLogin = searchParams.get("login");
        }
    }
    var genId = Bdf.generateId();
    Overlay.start({
        header: Bdf.Loc.escape("_ warning.multi.authentification_required"),
        content: Bdf.render("bdf:multiauthentification", {
            genId: genId,
            login: defaultLogin
        }),
        footer: Bdf.render("bdf:overlay-footer", {
            submit: {
                locKey: "_ submit.session.login"
            }}),
        escapeClose: false,
        clickClose: false,
        showClose: false,
        formAttrs: {
            action: Bdf.URL + "multi-admin",
            method: "POST"
        },
        ajaxForm: {
            dataType: "json",
            data: {
                json: "ping"
            },
            success: function (data, textStatus, jqXHR, $form) {
                var done = Bdf.checkError(data);
                if (done) {
                     Overlay.end($form);
                }
            }
        },
        afterEnd: function () {
            if (callback) {
                callback();
            }
        }
    });
};
