/* global Bdf,$$,Overlay */

Bdf.Overlay = {};


Bdf.Overlay.startRunning = function () {
    return Overlay.start({
        supplementaryClasses: {
            dialog: "overlay-RunningOverlay"
        },
        header: Bdf.Loc.escape("_ info.global.running"),
        content: " ",
        isWaiting: true,
        showClose: false
    });
};

Bdf.Overlay.showFqlEditor = function (xml, updateCallback) {
    var frameId = Bdf.generateId();
    var okId = Bdf.generateId();
    var jsonData = null;
    var isLoaded = false;
    var toBeInit = true;
    var overlayCallback = null;
    Overlay.start({
        header: Bdf.Loc.escape("_ title.selection.fqleditor"),
        content: Bdf.render("bdf:fqleditor", {
            frameId: frameId
        }),
        supplementaryClasses: {
            content: "global-fqleditor-OverlayContent"
        },
        footer: Bdf.render("bdf:overlay-footer", {
            submit: {
                type: "button",
                id: okId,
                locKey: '_ link.global.ok'
            }}),
        isWaiting: true,
        afterStart: function (overlayId, waitingCallback) {
            $$.one(frameId).addEventListener("load", function () {
                isLoaded = true;
                _initIframe(overlayId);
            });
            $.ajax({
                url: Bdf.URL + "selection",
                method: "POST",
                data: {
                    cmd: "FqlParser",
                    json: "fql",
                    xml: xml
                },
                dataType: Bdf.jsonDataType,
                success: function (data, textStatus) {
                    jsonData = data;
                    overlayCallback = waitingCallback;
                    _initIframe(overlayId);
                }
            });
        }
    });
    
    
    function _initIframe(overlayId) {
        if ((jsonData) && (isLoaded) && (toBeInit)) {
            toBeInit = false;
            overlayCallback();
            $$.one(frameId).contentWindow.FqlEditor.update(jsonData, overlayId);
            Overlay.addEscapeKeyHandler($$.one(frameId).contentDocument);
            $$(okId).click(function () {
                let result = $$.one(frameId).contentWindow.FqlEditor.getResult();
                Overlay.end(overlayId, function () {
                    updateCallback(result);
                });
            });
        }
    }
};

Bdf.Overlay.showFicheEditor = function (corpus, id, options) {
    var frameId = Bdf.generateId();
    var supplementaryClasses = {
        content: "global-ficheeditor-OverlayContent"
    };
    var isIdDefined;
    var changeDone = false;
    var page;
    var loadCallback;
    var doneCallback;
    var cancelCallback;
    var pageResultOptions = "overlay";
    var extraParametersString = "";
    var fichothequeUrl = "";
    if ((!id) || (id < 1)) {
        isIdDefined = false;
        id = null;
        page = "fiche-creation";
    } else {
        isIdDefined = true;
        page = "fiche-change";
    }
    if (options) {
        if (options.supplementaryClasses) {
            for(let propKey in options.supplementaryClasses) {
                if (propKey === "content") {
                    supplementaryClasses.content = supplementaryClasses.content + " " + options.supplementaryClasses["content"];
                } else {
                    supplementaryClasses[propKey] = options.supplementaryClasses[propKey];
                }
            }
        }
        if (options.loadCallback) {
            loadCallback = options.loadCallback;
        }
        if (options.doneCallback) {
            doneCallback = options.doneCallback;
        }
        if (options.cancelCallback) {
            cancelCallback = options.cancelCallback;
        }
        if (options.extraParameters) {
            for(let key in options.extraParameters) {
                let value = options.extraParameters[key];
                if (key === 'defval') {
                    for(let key2 in value) {
                        extraParametersString += `&defval-${key2}=${encodeURIComponent(value[key2])}`; 
                    }
                } else {
                    extraParametersString += `&${key}=${encodeURIComponent(value)}`; 
                }
            }
        }
        if (options.fichothequeUrl) {
            fichothequeUrl = options.fichothequeUrl;
        }
        if (options.resultToolbar) {
            pageResultOptions = options.resultToolbar;
        }
    }
    Overlay.start({
        content: Bdf.render("bdf:ficheeditor", {
            corpus: corpus,
            page: page,
            id: id,
            frameId: frameId,
            fichothequeUrl: fichothequeUrl,
            pageResultOptions: pageResultOptions,
            extraParameters: extraParametersString
        }),
        supplementaryClasses: supplementaryClasses,
        afterStart: function (overlayId) {
            $$(frameId).on("load", function (event) {
                try {
                    Bdf.Overlay.initClose(this.contentDocument, overlayId);
                    let iframeWindow = this.contentWindow;
                    if (iframeWindow.RESULT_ITEM) {
                        changeDone = true;
                        if (!isIdDefined) {
                            id = iframeWindow.RESULT_ITEM.id;
                            isIdDefined = true;
                        }
                    }
                    if (loadCallback) {
                        loadCallback(iframeWindow);
                    }
                } catch(error) {
                    Bdf.log(error);
                }
            });
        },
        beforeEnd: function () {
            try {
                let iframe = $$.one(frameId);
                try {
                    if (iframe.contentWindow.Bdf) {
                        return iframe.contentWindow.Bdf.confirmUnload();
                    }
                } catch(error) {
                    Bdf.log(error);
                }
            } catch(e) {
            }
            return true;
        },
        afterEnd: function () {
            if (changeDone) {
                if (doneCallback) {
                    doneCallback(corpus, id);
                }
            } else if (cancelCallback) {
                cancelCallback();
            }
        }
    });
};

Bdf.Overlay.showFichePopup = function (settings) {
    var popupId = Bdf.generateId();
    var iframeHref, blankHref, odtHref, editHref;
    var supplementaryClasses = {
        content: "global-fichepopup-OverlayContent"
    };
    var iframeCallback;
    if (settings) {
        if (settings.supplementaryClasses) {
            for(let propKey in settings.supplementaryClasses) {
                if (propKey === "content") {
                    supplementaryClasses.content = supplementaryClasses.content + " " + settings.supplementaryClasses["content"];
                } else {
                    supplementaryClasses[propKey] = settings.supplementaryClasses[propKey];
                }
            }
        }
        iframeHref = settings.iframeHref;
        blankHref = settings.blankHref;
        odtHref = settings.odtHref;
        if ((settings.corpus) && (settings.id)) {
            if (!iframeHref) {
                iframeHref = "fiches/" + settings.corpus + "-" + settings.id;
                if (settings.htmlTemplate) {
                    iframeHref = iframeHref + "-" + settings.htmlTemplate;
                }
                iframeHref = iframeHref + ".html";
            }
            if (!blankHref) {
                blankHref = "main-iframes?fiche=" + settings.corpus + "-" + settings.id;
                if (settings.htmlTemplate) {
                    blankHref = blankHref + "-" + settings.htmlTemplate;
                }
            }
            if (!odtHref) {
                odtHref = "fiches/" + settings.corpus + "-" + settings.id;
                if (settings.odtTemplate) {
                    odtHref = odtHref + "-" + settings.odtTemplate;
                }
                odtHref = odtHref + ".odt";
            }
        }
        if (settings.iframeCallback) {
            iframeCallback = settings.iframeCallback;
        }
    }
    var popupContext = {
        popupId: popupId,
        iframeHref: iframeHref,
        blankHref: blankHref,
        odtHref: odtHref
    };
    Overlay.start({
            content: Bdf.render("bdf:fichepopup", popupContext),
            supplementaryClasses: supplementaryClasses,
            afterStart: function (overlayId, waitingCallback) {
                $$(popupId, "iframe").on("load", function (event) {
                    Bdf.Overlay.initClose(this.contentDocument, overlayId);
                    if (iframeCallback) {
                        iframeCallback(this, popupContext);
                    }
                    let locationCheck = Bdf.checkIframeLocation(this);
                    if (locationCheck.withBorder) {
                        this.classList.add("global-fichepopup-WithBorder");
                    } else {
                        this.classList.remove("global-fichepopup-WithBorder");
                    }
                });
            }
    });
};

Bdf.Overlay.initClose = function (contentDocument, overlayId) {
    let closeButton = contentDocument.getElementById("button_overlay_close");
    let addHandler = true;
    if (closeButton) {
        closeButton.addEventListener('click', function () {
            Overlay.end(overlayId);
        });
        if ((closeButton.dataset.shortcutKey) && (closeButton.dataset.shortcutKey === "Escape")) {
            addHandler = false;
        }
    }
    if (addHandler) {
        Overlay.addEscapeKeyHandler(contentDocument);
    }
};

