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

Menu.ARGS = {
    bdfUser: {
      sphere: "",
      login: "",
      name: "",
      lang: "",
      locale: "",
      admin: false,
      status: "active"
    },
    links: {
        administration: false
    },
    actionGroupArray: []
};
Menu.corpusTree = [];

Menu.init = function (args) {
    Bdf.Api.init();
    var bdfUser = args.bdfUser;
    var corpusMap = new Map();
    var ficheGotoElementArray = new Array();
     $$("main_menu").html(Bdf.render("menu:menu", {
        bdfUser: bdfUser,
        links: args.links,
        actionGroupArray: args.actionGroupArray,
        readOnly: (bdfUser.status === "readonly")
    }));
    _initGoto();
    $$("menu_action_select").change(_doAction);
    $$("menu_fiche_create").click(function () {
        this.href = "edition?corpus=" + _getSelectedCorpusName() + "&page=fiche-creation";
        return true;
    });
    Bdf.registerFunction("menu:updateCorpusTree", _updateCorpusTree);
    Bdf.Ajax.loadSubsetTrees("corpus", false, function (subsetTrees) {
        _updateCorpusTree(subsetTrees.corpus);
    });
       

    function _doAction() {
        let option = this.options[this.selectedIndex];
        let target, url;
        if (!__checkValue()) {
            return;
        }
        $$("menu_action_redo").html(Bdf.render("menu:actionbutton", {
            url: url,
            text: option.text,
            target: target,
            action: option.dataset.action,
            iconSrc: option.dataset.iconSrc
        }));
        parent[target].document.location = url;
        this.selectedIndex = 0;


        function __checkValue() {
            let value = option.value;
            if (value.length === 0) {
                return false;
            }
            url = value;
            target = option.dataset.target;
            if (!parent[target]) {
                alert("Unknown target : " + target);
                return false;
            }
            return true;
        }
    }
    
    function _goTo(link) {
        let currentHref = link.getAttribute("href");
        if (currentHref.length > 1) {
            return true;
        }
        let corpus = corpusMap.get(_getSelectedCorpusName());
        if (!corpus) {
            return false;
        }
        let gotoValue = $$.one("menu_fiche_goto").value.trim();
        if (!gotoValue) {
            _alertGoto();
            return false;
        }
        let gotoId = parseInt(gotoValue);
        if (isNaN(gotoId)) {
            if (corpus._isIdalphaSatellite) {
                Bdf.api.loadMotcle({
                    thesaurus: corpus.master.name,
                    idalpha: gotoValue,
                    ignoreLogError: true,
                    callback: function (data) {
                        Bdf.log(data);
                        if (data.motcle) {
                            _updateGoto(corpus.name, data.motcle.id);
                            link.click();
                        } else {
                            alert(Bdf.Loc.get("_ error.unknown.id", gotoValue));
                        }
                    }
                });
                return false;
            } else {
                _alertGoto();
            }
            return false;
        } else {
            if (gotoId < 1) {
                _alertGoto();
                return false;
            } else {
                _updateGoto(corpus.name, gotoId);
                return true;
            }
        }
    }
    
    function _alertGoto() {
        alert(Bdf.Loc.get("_ error.wrong.goto"));
    }
    
    function _updateCorpusTree(corpusTree) {
        Menu.corpusTree = corpusTree;
        corpusMap.clear();
        let currentCorpus = _getSelectedCorpusName();
        __complete(corpusTree, "");
        $$("menu_fiche_select").html(Bdf.render("menu:corpustree", {
            corpusTree: corpusTree
        }));
        if (corpusTree.length > 0) {
            $$("menu_fiche").removeClass("invisible");
        } else {
            $$("menu_fiche").addClass("invisible");
        }
        
        
        function __complete(array, indent) {
            for(let node of array) {
                node.indent = indent;
                if (node.node === "group") {
                    __complete(node.array, indent + "\u00A0 \u00A0 ");
                } else {
                    if (node.name === currentCorpus) {
                        node._selected = true;
                    }
                    corpusMap.set(node.name, node);
                    if ((node.master) && (node.master.type) && (node.master.type === "idalpha")) {
                        node._isIdalphaSatellite = true;
                    }
                }
            }
        }
    }
    
    function _getSelectedCorpusName() {
        let select = $$.one("menu_fiche_select");
        if (select.selectedIndex < 0) {
            return "";
        }
        return select.options[select.selectedIndex].value;
    }
    
    function _initGoto() {
        let $gotoElements = $$({ficheGotoKey: true});
         $gotoElements.click(function () {
            return _goTo(this);
        });
         $gotoElements.each(function (index, element) {
             ficheGotoElementArray.push(element);
         });
        $$("menu_fiche_goto").on("input", function () {
            for(let element of ficheGotoElementArray) {
                element.href = "#";
                element.setAttribute("href", "#");
            }
        });
    }
    
    function _updateGoto(corpusName, ficheId) {
        for(let element of ficheGotoElementArray) {
            element.href = Menu.toHref(element.dataset.ficheGotoKey, corpusName, ficheId);
        }
    }
    
};

Menu.toHref = function (key, corpusName, ficheId) {
    switch(key) {
        case "read":
            return "fiches/" + corpusName + "-" + ficheId + ".html";
        case "write":
            return "edition?corpus=" + corpusName + "&id=" + ficheId + "&page=fiche-change";
        case "indexation":
            return "edition?corpus=" + corpusName + "&id=" + ficheId + "&page=fiche-indexation";
        case "selection":
            return "selection?corpus=" + corpusName + "&id=" + ficheId + "&page=main:fiches&cmd=UserSelectionByFiche";
        default:
            return "#";
    }
};


/******************************************************************************
 * Initialisation
 ******************************************************************************/

$(function () {
    Bdf.initTemplates();
    Menu.init(Menu.ARGS);
});