/* global Bdf,$$ */
/**
 * Objet global définissant l'espace de nom Ficheframe
 * 
 * @namespace Ficheframe,Bdf
 */
var Ficheframe = {};

Ficheframe.backgroundColor = "#f4f4f4";

Ficheframe.ARGS = {
    goto: "",
    pageResultOptions: ""
};

Ficheframe.testToolbar = function (settings) {
    var iframe = settings.iframe;
    var toolbarId = settings.toolbarId;
    var fieldeditId = settings.fieldeditId;
    var callback = settings.callback;
    var pageResultOptions = settings.pageResultOptions;
    var contentWindow = iframe.contentWindow;
    var editTarget, tocTarget, startingLeft;
    if (settings.hasOwnProperty("editTarget")) {
        editTarget = settings.editTarget;
    } else {
        editTarget = iframe.name;
    }
    if (settings.hasOwnProperty("tocTarget")) {
        tocTarget = settings.tocTarget;
    } else {
        tocTarget = iframe.name;
    }
    if (settings.hasOwnProperty("startingLeft")) {
        startingLeft = settings.startingLeft;
    } else {
        startingLeft = Ficheframe.GotoManager.getStartingLeft(fieldeditId);
    }
    _showToolbar(false);
    var buttonId = "ficheframe_button_ficheedit";
    var ficheInfo = Ficheframe.Info.parse(iframe);
    if (!ficheInfo) {
        return;
    }
    var gotoManager = new Ficheframe.GotoManager(iframe, fieldeditId, startingLeft);
    var toc = Ficheframe.checkToc(contentWindow.document);
    ficheInfo.checkEditable(function () {
        gotoManager.init(ficheInfo.editable, _updateGoto);
        let html = Bdf.render("ficheframe:toolbar", {
            ficheInfo: ficheInfo,
            toc: toc,
            editTarget: editTarget,
            tocTarget: tocTarget,
            pageResultOptions: pageResultOptions
        });
        $$(toolbarId).html(html);
        if (html.length > 0) {
            _showToolbar(true);
            $(contentWindow).on('pagehide', function(e) {
                _showToolbar(false);
                gotoManager.hide();
            });
            if (ficheInfo.editable) {
                let editLink = $$.one(buttonId);
                let originalHref = editLink.href;
                if (toc.length > 0) {
                    $(contentWindow).on("scroll", function(event) {
                        let currentTocItem = Ficheframe.getCurrentTocItem(contentWindow, toc);
                        $(".ficheframe-toc-Active").removeClass("ficheframe-toc-Active");
                        editLink.href = originalHref;
                        if (currentTocItem) {
                            $$("linkto:" + currentTocItem.id).addClass("ficheframe-toc-Active");
                            if (currentTocItem.editGoto) {
                                editLink.href = originalHref + "&goto=" + currentTocItem.editGoto;
                            }
                        }
                    });
                }
            }
        }
        if (callback) {
            callback();
        }
    });

    
    function _updateGoto (position, top, left) {
        $$(fieldeditId).html(Bdf.render("ficheframe:fieldedit", {
            corpusName: position.checkCorpusName(ficheInfo.corpus),
            ficheId: position.checkFicheId(ficheInfo.id),
            editTarget: editTarget,
            goto: position.goto,
            pageResultOptions: pageResultOptions,
            fichothequeUrl: ficheInfo.fichothequeUrl
        })).css("top", top).css("left", left);
    }
     
    function _showToolbar(display) {
        Ficheframe.show(toolbarId, display);
    }

};


Ficheframe.show = function (elementId, display) {
    if (display) {
        $$(elementId).removeClass("hidden");
    } else {
        $$(elementId).addClass("hidden");
    }
};

Ficheframe.checkToc = function (document) {
    let array = new Array();
    $$(document, {bdfMilestone: true}).each(function (index, element) {
        let milestoneType = element.dataset.bdfMilestone;
        let editGoto;
        let $headings;
        switch(milestoneType) {
            case "satellite":
                editGoto = "satellite_" + element.dataset.bdfSatellite;
                $headings = $(element).children("h1");
                break;
            case "comment":
                editGoto = element.dataset.bdfComponentName;
                let $satellite = $(element).parents($$.toCssSelector({bdfMilestone: "satellite"}));
                if ($satellite.length > 0) {
                    editGoto = "satellite_" + $satellite[0].dataset.bdfSatellite + "/" + editGoto;
                }
                $headings = $(element).find("h2");
                break;
            case "heading":
                if (element.dataset.bdfGoto) {
                    editGoto = element.dataset.bdfGoto;
                }
                $headings = $(element);
                break;
        }
        if ($headings) {
            $headings.each(function (index2, element2) {
                let id = element2.id;
                if (!id) {
                    id = Bdf.generateId();
                    element2.id = id;
                }
                let $element2 = $(element2);
                let text = $element2.text();
                if (!$element2.is(":hidden")) {
                    array.push({
                        id: id,
                        text: text,
                        element: element2,
                        editGoto: editGoto
                    });
                }
            });
        }
    });
    return array;
};

Ficheframe.getCurrentTocItem = function (contentWindow, toc) {
    let threshold = contentWindow.innerHeight * 2 / 3;
    let scrollTop = $(contentWindow.document).scrollTop();
    let currentTocItem = false;
    for (let i = toc.length-1; i >= 0; i--) {
        let tocItem = toc[i];
        if (scrollTop > $(tocItem.element).offset().top - threshold) {
            currentTocItem = tocItem;
            if (i > 0) {
                let previousTocItem = toc[i - 1];
                let $previousEl = $(previousTocItem.element);
                let previousBottom = $previousEl.offset().top + $previousEl.height() + (threshold / 3);
                if (previousBottom > scrollTop) {
                    currentTocItem = previousTocItem;
                }
            }
            break;
        }
    }
    return currentTocItem;
};

Ficheframe.fichePopupIframeCallback = function (iframe, popupContext) {
    Ficheframe.testToolbar({
        iframe: iframe,
        toolbarId: popupContext.popupId + "_iframe_toolbar",
        fieldeditId: popupContext.popupId + "_iframe_fieldedit",
        pageResultOptions: "overlay"
    });
};