/* global Bdf,Ficheform,$$,Fql */

Ficheform.CorpusInclude.Manager = function (entryKey, type, corpusName, withWeight) {
    this.entryKey = entryKey;
    this.type = type;
    if (type === "liage") {
        this.isSpecialLiage = true;
        this.corpusName = "";
        this.withWeight = true;
        this.itemsAtStart = 0;
    } else {
        this.isSpecialLiage = false;
        this.corpusName = corpusName;
        this.withWeight = withWeight;
        this.hereMap = new Map();
    }
    this.toolsId = null;
};

Ficheform.CorpusInclude.Manager.map = new Map();

Ficheform.CorpusInclude.Manager.prototype.checkHidden = function () {
    var entry = Ficheform.entry(this.entryKey);
    var toolsId = this.toolsId;
    var size;
    if (this.isSpecialLiage) {
        size = this.itemsAtStart;
    } else {
        size = this.hereMap.size;
        Ficheform.checkEnumerationCell(entry, size);
    }
    if (toolsId) {
        if (size > 1) {
            $$(toolsId, "sort_asc").removeClass("hidden");
            $$(toolsId, "sort_desc").removeClass("hidden");
        } else {
            $$(toolsId, "sort_asc").addClass("hidden");
            $$(toolsId, "sort_desc").addClass("hidden");
        }
    }
};

Ficheform.CorpusInclude.Manager.prototype.pioche = function (inputId) {
    var entry = Ficheform.entry(this.entryKey);
    var subsets = this.corpusName;
    var limit = entry.dataset.ficheformLimit;
    if (!limit) {
        limit = -1;
    }
    var url = "pioche?page=fiche&subsets=" + subsets + "&appelant=" + inputId + "&limit=" + limit;
    if (subsets) {
        url = url + "&buttons=fichecreation" ;
    }
    Ficheform.openDialog(url,"pioche_" + this.entryKey, 430,510);
};

Ficheform.CorpusInclude.Manager.prototype.sort = function (desc) {
    var entry = Ficheform.entry(this.entryKey);
    var $container;
    switch(this.type) {
        case "table":
            $container = $$(entry, {ficheformRole: "fiche-rows"});
            break;
        case "check":
            $container = $$(entry,{ficheformRole: "item-choices"});
            break;
        default:
            return;
    }
    var array = new Array();
    var previousFicheIdArray = new Array();
    $container.children().each(function (index, element) {
        let ficheId = parseInt(element.dataset.ficheformItemId);
        previousFicheIdArray.push(ficheId);
        array.push({
            ficheId: ficheId,
            element: element
        });
    });
    var length = array.length;
    if (length < 2) {
        return false;
    }
    array = array.sort(function (obj1, obj2) {
        let sortValue = _sort(obj1, obj2);
        if (desc) {
            sortValue = -sortValue;
        }
        return sortValue;
    });
    if (!_hasChange()) {
        return false;
    }
    let $current = $(array[0].element);
    $container.prepend($current);
    for(let i = 1; i < length; i++) {
        let $next = $(array[i].element);
        $current.after($next);
        $current = $next;
    }
    Ficheform.signalChange();
    return true;
    
    function _sort(obj1, obj2) {
        if (obj1.ficheId < obj2.ficheId) {
            return -1;
        }
        if (obj1.ficheId > obj2.ficheId) {
            return 1;
        }
        return 0;
    }
    
    function _hasChange() {
        for(let i = 0; i < length; i++) {
            if (previousFicheIdArray[i] !== array[i].ficheId) {
                return true;
            }
        }
        return false;
    }
};

Ficheform.CorpusInclude.Manager.prototype.setHere = function (id) {
    return this.hereMap.set(parseInt(id), true);
};

Ficheform.CorpusInclude.Manager.prototype.isHere = function (fiche) {
    return this.hereMap.has(fiche.id);
};

Ficheform.CorpusInclude.Manager.init = function (entry, type) {
    var entryKey = entry.dataset.ficheformKey;
    var manager = new Ficheform.CorpusInclude.Manager(entryKey, type, entry.dataset.subsetName, entry.dataset.ficheformWithweight);
    var corpusName = manager.corpusName;
    var noTab = Ficheform.getOption("noTab");
    _initDirectInput();
    _initWeight();
    switch(type) {
        case "liage":
            _initLiage();
            break;
        case "check":
            _initCheckCorpus();
            break;
        case "table":
            _initTableCorpus();
            break;
    }
    manager.checkHidden();
    Ficheform.CorpusInclude.Manager.map.set(entryKey, manager);
    return manager;
    
    function _initDirectInput() {
        let $directInput = $$(entry, {ficheformRole: "fiche-directinput"});
        if ($directInput.length === 0) {
            return;
        }
        let inputId = $$.one($directInput, {ficheformRole: "textinput"}).id;
        let buttonId = Bdf.generateId();
        let locKey, locValue;
        if (manager.isSpecialLiage) {
            locKey = "_ link.pioche.fiche_all";
            locValue = "";
        } else {
            locKey = "_ link.pioche.fiche_one";
            locValue = Bdf.Loc.get("subset:corpus_" + corpusName);
        }
        $directInput.append(Bdf.render("bdf:button-transparent32", {
            buttonId: buttonId,
            action: "action-ficheform-Fiche",
            locKey: locKey,
            locValue: locValue,
            noTab: noTab
        }));
        $$(buttonId).click(function () {
            manager.pioche(inputId);
        });        
    }
    
    function _initWeight() {
        if (manager.withWeight) {
            Ficheform.initWeightInput($$(entry, {ficheformRole: "cell-enumeration"}));
        }
    }
    
    function _initLiage() {
        let $choices = $$(entry, {ficheformRole: "item-choices"});
        let $choiceItems = $$($choices, {ficheformRole: "item-choice"});
        manager.itemsAtStart = $choiceItems.length;
        $choiceItems.each(function (index, element) {
            let genId = Bdf.generateId();
            $$(element, {_element: "label"}).after(Bdf.render("ficheform:include/choicebuttons", {
                genId: genId,
                noTab: noTab
            }));
            Ficheform.initOrderButtons(genId, element);
        });
    }
    
    function _initCheckCorpus() {
        _initTools();
        _initSearchArea(__addChoice);
        let $choices = $$(entry, {ficheformRole: "item-choices"});
        $$($choices, {ficheformRole: "item-choice"}).each(function (index, element) {
           __initChoice(element);
        });
        
        function __initChoice(element) {
            manager.setHere(element.dataset.ficheformItemId);
            let genId = Bdf.generateId();
            $$(element, {_element: "label"}).after(Bdf.render("ficheform:include/choicebuttons", {
                genId: genId,
                noTab: noTab
            }));
            Ficheform.initOrderButtons(genId, element);
        }
        
        function __addChoice(subsetName, id) {
            Bdf.api.loadFiche({
                corpus: subsetName,
                id: id,
                requestParameters: {
                    properties: "special:phrases"
                },
                callback: function (data) {
                    let fiche = data.fiche;
                    $choices.append(Bdf.render("ficheform:include/itemchoice", {
                        itemId: id,
                        checkboxName: entryKey,
                        checkboxValue: id,
                        checkboxId: Bdf.generateId(),
                        withWeight: manager.withWeight,
                        number: fiche.properties.number,
                        title: fiche.title
                    }));
                    __initChoice($$.one($choices, {ficheformItemId: id}));
                    manager.checkHidden();
                    Ficheform.signalChange();
                }
           });
        }
    }
    
    function _initTableCorpus() {
        let parentCorpus = Ficheform.getCurrentCorpus(entry);
        _initTools();
        _initSearchArea(__addRow);
        let ficheRows = $$.one(entry, {ficheformRole: "fiche-rows"});
        let colDefArray = Ficheform.CorpusInclude.parseColDefList(ficheRows.dataset.ficheformColDefList);
        $$(ficheRows, {ficheformRole: "fiche-row"}).each(function (index, element) {
           __initRow(element); 
        });
        
        function __initRow(tr) {
            let ficheId = tr.dataset.ficheformItemId;
            manager.setHere(ficheId);
            let genId = Bdf.generateId();
            $$(tr, {ficheformRole: "fiche-row-buttons"}).html(Bdf.render("ficheform:include/rowbuttons", {
                genId: genId,
                noTab: noTab
               }));
            Ficheform.initOrderButtons(genId, tr);
            $$(genId, "edit").click(function () {
                Bdf.Overlay.showFicheEditor(corpusName, ficheId, {
                    doneCallback: function (subsetName, id) {
                        Bdf.api.loadFiche({
                            corpus: subsetName,
                            id: id,
                            requestParameters: {
                                properties: "special:table",
                                contextcorpus: parentCorpus
                            },
                            callback: function (data) {
                                let fiche = data.fiche;
                                let cellArray = [];
                                for(let colDef of colDefArray) {
                                    if (fiche.properties.hasOwnProperty(colDef.name)) {
                                        cellArray.push(fiche.properties[colDef.name]);
                                    } else {
                                        cellArray.push("");
                                    }
                                }
                                $$(ficheRows, {ficheformItemId: id}).children().each(function (index, element) {
                                    if (index > 1) {
                                        $(element).html(cellArray[index - 2]);
                                    }
                                });
                            }
                        });
                    }
                });
            });
            $$(genId, "remove").click(function () {
                $$(tr, {_element: "input", _type: "checkbox"}).prop("checked", false);
                $(tr).addClass("ficheform-fichetable-Remove");
                $$(genId, "remove").addClass("hidden");
                $$(genId, "add").removeClass("hidden");
            });
            $$(genId, "add").click(function () {
                $$(tr, {_element: "input", _type: "checkbox"}).prop("checked", true);
                $(tr).removeClass("ficheform-fichetable-Remove");
                $$(genId, "remove").removeClass("hidden");
                $$(genId, "add").addClass("hidden");
            });
        }
        
        function __addRow(subsetName, id) {
            Bdf.api.loadFiche({
                corpus: subsetName,
                id: id,
                requestParameters: {
                    properties: "special:table",
                    contextcorpus: parentCorpus
                },
                callback: function (data) {
                    let fiche = data.fiche;
                    let cellArray = [];
                    for(let colDef of colDefArray) {
                        let value = "";
                        if (fiche.properties.hasOwnProperty(colDef.name)) {
                            value = fiche.properties[colDef.name];
                        }
                        cellArray.push({
                            value: value,
                            format: colDef.format
                        });
                    }
                    $(ficheRows).append(Bdf.render("ficheform:include/ficherow", {
                        itemId: id,
                        checkboxName: entryKey,
                        checkboxValue: id,
                        cellArray: cellArray
                    }));
                    __initRow($$.one(ficheRows, {ficheformItemId: id}));
                    manager.checkHidden();
                    Ficheform.signalChange();
                }
           });
        }
    }
    
    function _initTools() {
        let toolsId = Bdf.generateId();
        manager.toolsId = toolsId;
        $$(entry, {ficheformRole: "searchcontainer"}).prepend(Bdf.render("ficheform:include/tools", {
            noTab: noTab,
            toolsId: toolsId
        }));
        $$(toolsId, "sort_asc").click(function () {
            manager.sort(false);
        });
        $$(toolsId, "sort_desc").click(function () {
            manager.sort(true);
        });
    }
    
    function _initSearchArea(addCallback) {
        let withCreate = Ficheform.ARGS.permissions.hasOwnProperty(corpusName);
        let searchInputId = Bdf.generateId();
        let createButtonId = (withCreate)?Bdf.generateId():0;
        let searchAnchorId = Bdf.generateId();
        let createTitle;
        if ((withCreate) && (Bdf.Loc.contains("newfiche:corpus_" + corpusName))) {
            createTitle = Bdf.Loc.get("newfiche:corpus_" + corpusName);
        }
        $$(entry, {ficheformRole: "searchcontainer"}).prepend(Bdf.render("ficheform:include/searcharea", {
            noTab: noTab,
            createButtonId: createButtonId,
            searchInputId: searchInputId,
            withCreate: withCreate,
            createTitle: createTitle
        }));
        $(entry).append(Bdf.render("ficheform:include/searchanchor", {
            searchAnchorId: searchAnchorId,
            isCell: true
        }));
        Ficheform.initSearchInput(searchInputId, searchAnchorId, function (input) {
            Ficheform.delayFunction(input.id, function () {
                let query = input.value.trim();
                if (query) {
                    __search(query);
                } else {
                    $$(searchAnchorId).html("");
                }
            });
        });
        $$(searchAnchorId).on("click", $$.toCssSelector({action: "itemadd"}), function () {
            addCallback(corpusName, this.dataset.id);
            $$(searchAnchorId).html("");
            $$(searchInputId).val("");
            return false;
        });
        $$(createButtonId).click(function () {
            Bdf.Overlay.showFicheEditor(corpusName, -1, {
                doneCallback: addCallback
            });
        });
        
        function __search(query) {
            Bdf.api.loadFicheArray({
                ficheQuery: {
                    corpus: corpusName,
                    content: {
                        scope: Fql.SCOPE_TITLE,
                        q: query,
                        type: Fql.QTYPE_SIMPLE
                    }
                },
                requestParameters: {
                    sort: "id-desc",
                    limit: 50
                },
                callback: function (data) {
                    let ficheArray = data.array;
                    if (ficheArray.length === 0) {
                        __updateSearch(Bdf.render("ficheform:include/searchinfo", {locKey: '_ info.edition.noresult'}));
                    } else {
                        let first = true;
                        for(let fiche of ficheArray) {
                            if (manager.isHere(fiche)) {
                                fiche._here = true;
                            } else if (first) {
                                fiche._selected = first;
                                first = false;
                            }
                            fiche._title = fiche.id + " – " + fiche.title;
                        }
                        __updateSearch(Bdf.render("ficheform:include/searchlist", {array: ficheArray}));
                    }
                }
            });
        }
        
        function __updateSearch(html) {
            $$(searchAnchorId).removeClass("hidden").html(html);
        }
    }
};