/* global Fql,Fapi,Bdf,$$,Overlay,Index,Ficheframe */

Index.Search = {};

Index.Search.SORT_ARRAY = [
	{
		name: "creationdate-desc",
		locKey: "_ label.selection.sorttype_creationdate"
	},
	{
		name: "title-asc",
		locKey: "_ label.selection.sorttype_title"
	},
	{
		name: "id-asc",
		locKey: "_ label.selection.sorttype_id"
	}
];
Index.Search.SCOPE_ARRAY = [
	{
		name: "title",
		locKey: "_ label.selection.scope_title"
	},
	{
		name: "head",
		locKey: "_ label.selection.scope_head"
	},
	{
		name: "fiche",
		locKey: "_ label.selection.scope_fiche"
	}
];

Index.Search.initSubmit = function (formId, options) {
    $$(formId).submit(function(event) {
        event.preventDefault();
        let q = this["q"].value;
        if (q) {
            q = q.trim();
        }
        if (q) {
            let scopeSelect = this["scope"];
            let contentScope = scopeSelect.options[scopeSelect.selectedIndex].value;
            let sortSelect = this["sort"];
            let sortType = sortSelect.options[sortSelect.selectedIndex].value;
            Index.Search.show(q, contentScope, sortType, options);
        }
    });
};

Index.Search.show = function (q, contentScope, sortType, options) {
    var formId = Bdf.generateId();
    var targetArray = new Array();
    if ((options) && (options.fichothequeScope)) {
        _initScopeTargets();
    } else {
        _initDefaultTargets();
    }
    var max = targetArray.length;
    var count = 0;
    var contentScopeArray = Index.toOptionArray(Index.Search.SCOPE_ARRAY, contentScope);
    var sortTypeArray = Index.toOptionArray(Index.Search.SORT_ARRAY, sortType);
    Overlay.start({
        content: Bdf.render("index:overlay/search", {
            q: q,
            formId: formId,
            targetArray: targetArray,
            contentScopeArray: contentScopeArray,
            sortTypeArray: sortTypeArray,
            iframeName: "search_fiche"
        }),
        isWaiting: true,
        supplementaryClasses: {
            content: "index-search-OverlayContent"
        },
        afterStart: function (overlayId, waitingCallback) {
            $$(formId, "search").submit(function(event) {
                event.preventDefault();
                let newQ = this["q"].value;
                if (newQ) {
                        newQ = newQ.trim();
                }
                if (newQ) {
                    count = 0;
                    q = newQ;
                    let scopeSelect = this["scope"];
                    contentScope = scopeSelect.options[scopeSelect.selectedIndex].value;
                    let sortSelect = this["sort"];
                    sortType = sortSelect.options[sortSelect.selectedIndex].value;
                    $$(formId, "button_submit").prop("disabled", true);
                    for(let target of targetArray) {
                        $$(formId, "target", target.name).html("");
                        $$(formId, "fichecount", target.name).text("");
                       _search(target, waitingCallback);
                    }
                }
            });
            for(let target of targetArray) {
                _search(target, waitingCallback);
            }
            Index.Search.initViewerIframe(formId);
        }
    });
    
    function _search(target, waitingCallback) {
        var ficheQueryArray = new Array();
        for(let query of target.queries) {
            let fq = Object.assign({
                content: {
                    scope: contentScope,
                    q: q,
                    type: "simple"
                }
            }, query);
            ficheQueryArray.push(new Fql.FicheQuery(fq));
        }
        Fapi.Ajax.loadFiches(new Fapi(target.name + "/"), ficheQueryArray, {
            callback: function (data) {
                count++;
                if (count === max) {
                    $$(formId, "button_submit").prop("disabled", false);
                    waitingCallback();
                }
                $$(formId, "fichecount", target.name).text("(" + data.fiches.count + ")");
                let $target = $$(formId, "target", target.name);
                $target.html(Bdf.render("index:search-results", {
                    fichotheque: target.name,
                    fiches: data.fiches,
                    iframeName: "search_fiche"
                }, {getFicheUrl: function (fiche) {
                    return target.name + "/fiches/" + fiche.corpus + "-" + fiche.id
                            + _getCustomTemplate(target.name, fiche.corpus, "html")
                            + ".html";
                }}));
                $$($target, {role: "fiche"}).click(function() {
                    let ficheLink = this;
                    Index.Search.viewFiche(ficheLink, formId, _getCustomTemplate);
                });
            },
            requestParameters: {
                sort: sortType
            }
        });
    }
    
    function _getCustomTemplate(fichotheque, corpus, type) {
        let template = "";
        if ((options) && (options.getTemplate)) {
            template = options.getTemplate(fichotheque, corpus, type);
        }
        if (template) {
            return "-" + template;
        }
        return "";
    }
    
    function _initDefaultTargets() {
        for(let fichotheque of Index.FICHOTHEQUE_MAP.values()) {
            let title = fichotheque.phrases.long;
            if (!title) {
                title = fichotheque.title;
            }
            targetArray.push({
                name: fichotheque.name,
                title: title,
                queries: [{}],
                fichotheque: fichotheque
            });
        }
    }
    
    function _initScopeTargets() {
        for(let scope of options.fichothequeScope) {
            let fichotheque = Index.FICHOTHEQUE_MAP.get(scope.name);
            if (fichotheque) {
                let title = fichotheque.phrases.long;
                if (!title) {
                    title = scope.name;
                }
                targetArray.push({
                    name: scope.name,
                    title: title,
                    queries: scope.queries,
                    fichotheque: fichotheque
                });
            }
        }
    }
    
};

Index.Search.initViewerIframe = function (formId) {
    $$(formId, "iframe").on("load", function (event) {
        let iframe = this;
        Ficheframe.testToolbar({
                iframe: iframe,
                toolbarId: formId + "_iframe_toolbar",
                fieldeditId: formId + "_iframe_fieldedit",
                pageResultOptions: "standalone"
        });
        let locationCheck = Bdf.checkIframeLocation(iframe);
        if (locationCheck.withBorder) {
            iframe.classList.add("index-search-WithBorder");
        } else {
            iframe.classList.remove("index-search-WithBorder");
        }
    });
};

Index.Search.viewFiche = function (ficheLink, formId, getCustomTemplate) {
    let fichotheque = ficheLink.dataset.fichotheque;
    let corpus = ficheLink.dataset.corpus;
    let id = ficheLink.dataset.id;
    let blankHref = fichotheque + "/main-iframes?fiche=" + corpus + "-" + id + getCustomTemplate(fichotheque, corpus, "html");
    let odtHref = fichotheque + "/fiches/" + corpus + "-" + id + getCustomTemplate(fichotheque, corpus, "odt") + ".odt";
    $$(formId, "button_refresh").attr("href", ficheLink.href).removeClass("hidden");
    $$(formId, "button_blank").attr("href", blankHref).removeClass("hidden");
    $$(formId, "button_odt").attr("href", odtHref).removeClass("hidden");
};
