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

Ficheform.ThesaurusInclude = {};

Ficheform.ThesaurusInclude.getThesaurusInfo = function (element) {
    let entryKey = element.dataset.ficheformKey;
    let thesaurusName = element.dataset.subsetName;
    let isExternalSource;
    if (element.dataset.ficheformExternalsource) {
        isExternalSource = true;
    } else {
        isExternalSource = false;
    }
    let currentCorpus = Ficheform.getCurrentCorpus(element);
    let inputId = $$.one(element, {ficheformRole: "textinput"}).id;
    return {
        entryKey:  entryKey,
        thesaurusName: thesaurusName,
        isExternalSource: isExternalSource,
        currentCorpus: currentCorpus,
        inputId: inputId,
        ficheform: {
            limit: element.dataset.ficheformLimit,
            wanted: element.dataset.ficheformWanted,
            idalphaStyle: element.dataset.ficheformIdalphastyle,
            withWeight: element.dataset.ficheformWithweight
        }
    };
};

Ficheform.ThesaurusInclude.init = function () {
    Bdf.Api.init();
    $$({ficheformEntry: "thesaurus-include"}).each(function (index, element) {
        let thesaurusInfo = Ficheform.ThesaurusInclude.getThesaurusInfo(element);
        _initMotclePioche(element, thesaurusInfo);
        if ($$(element, {ficheformRole: "cell-enumeration"}).length > 0) {
            _initFicheStyle(element, thesaurusInfo);
        } else {
            _initMotcleSuggestion(element, thesaurusInfo);
        }
    });

    function _initMotclePioche(element, thesaurusInfo) {
        let buttonId = Bdf.generateId();
        let action, locKey;
        if (thesaurusInfo.isExternalSource) {
            action = "action-ficheform-ExternalSource";
            locKey = "_ link.pioche.externalsource";
        } else {
            action = "action-ficheform-Motcle";
            locKey = "_ link.pioche.motcle_one";
        }        
        $$(element, {ficheformRole: "motcle-input"}).append(Bdf.render("bdf:button-transparent32", {
            buttonId: buttonId,
            action: action,
            locKey: locKey,
            locValue:  Bdf.Loc.get("subset:thesaurus_" + thesaurusInfo.thesaurusName),
            noTab: Ficheform.getOption("noTab")
        }));
        $$(buttonId).click(function () {
            __pioche();
        });
        
        function __pioche() {
            let page;
            if (thesaurusInfo.isExternalSource) {
                page = "externalsource";
            } else {
                page = "motcle";
            }
            let limit = thesaurusInfo.ficheform.limit;
            if (!limit) {
                limit = -1;
            }
            let url = "pioche?page=" + page + "&subsets=" + thesaurusInfo.thesaurusName + "&appelant=" + thesaurusInfo.inputId + "&limit=" + limit;
            url = url + "&junction=corpus_" + thesaurusInfo.currentCorpus;
            let wanted = thesaurusInfo.ficheform.wanted;
            if (wanted) {
                url = url + "&wanted=" +  wanted;
            }
            Ficheform.openDialog(url,"pioche_"+ thesaurusInfo.entryKey, 430,510);
        }
    }
    
    function _initMotcleSuggestion(element, thesaurusInfo) {
        let searchAnchorId = Bdf.generateId();
        let $entry = $(element);
        $entry.append(Bdf.render("ficheform:include/searchanchor", {
            searchAnchorId: searchAnchorId,
            isCell: true
        }));
        $$(searchAnchorId).on("click", $$.toCssSelector({action: "itemadd"}), function () {
            let value = this.dataset.value;
            let input = $$.one(thesaurusInfo.inputId);
            let activePosition =  __extractActive(input);
            let currentValue = input.value;
            let prefix = "";
            let suffix = "; ";
            let newCaretPosition = -1;
            if (activePosition.previous > - 1) {
                prefix = currentValue.substring(0, activePosition.previous + 1) + " ";
            }
            if (activePosition.next > -1) {
                suffix = currentValue.substring(activePosition.next);
                let start = prefix + value;
                newCaretPosition = start.length + 1;
            }
            input.value = prefix + value + suffix;
            $$(searchAnchorId).html("");
            if (newCaretPosition === -1) {
                input.selectionStart = input.value.length;
            } else {
                input.selectionStart = newCaretPosition;
                input.selectionEnd = newCaretPosition;
            }
            input.focus();
            return false;
        });
        Ficheform.initSearchInput(thesaurusInfo.inputId, searchAnchorId, function (input) {
            Ficheform.delayFunction(input.id, function () {
                let extraction = __extractActive(input);
                if (extraction.activeTerm) {
                    __searchThesaurus(extraction.activeTerm);
                } else {
                    $$(searchAnchorId).html("");
                }
            });
        });
        
        function __extractActive(input) {
            let activeTerm = input.value;
            let caretPosition = input.selectionStart;
            let next = activeTerm.indexOf(';', caretPosition);
            if (next > -1) {
                activeTerm = activeTerm.substring(0, next);
            }
            let previous = activeTerm.lastIndexOf(';', caretPosition);
            if (previous > -1) {
                activeTerm = activeTerm.substring(previous + 1);
            }
            activeTerm = activeTerm.trim();
            return {
                next: next,
                previous: previous,
                activeTerm: activeTerm
            };
        }
        
        function __searchThesaurus(query) {
            let thesaurusName = thesaurusInfo.thesaurusName;
            Bdf.api.loadMotcleArray({
                motcleQuery: {
                    thesaurus: thesaurusName,
                    content: {
                        scope: Fql.SCOPE_IDALPHA_WITH,
                        q: query,
                        type: Fql.QTYPE_SIMPLE
                    },
                    status: "active"
                },
                requestParameters: {
                    limit: 50,
                    sortprecedence: _toSortPrecedence(query)
                },
                callback: function (data) {
                    let motcleArray = data.array;
                    if (motcleArray.length === 0) {
                        __updateSearch(Bdf.render("ficheform:include/searchinfo", {locKey: '_ info.edition.nosuggestion'}));
                    } else {
                        let first = true;
                        for(let motcle of motcleArray) {
                            if (first) {
                                motcle._selected = true;
                                first = false;
                            } else {
                                motcle._selected = false;
                            }
                            motcle._title = Ficheform.concatMotcleTitle(motcle, thesaurusInfo.ficheform.idalphaStyle);
                        }
                        __updateSearch(Bdf.render("ficheform:include/searchlist", {array: motcleArray}));
                    }
                }
            });
        }
        
        function __updateSearch(html) {
            $$(searchAnchorId).removeClass("hidden").html(html);
        }
        
    }


    function _initFicheStyle(element, thesaurusInfo) {
        let hereMap = new Map();
        let thesaurusName = thesaurusInfo.thesaurusName;
        let entryKey = thesaurusInfo.entryKey;
        let $entry = $(element);
        __initSearchArea();
        if (thesaurusInfo.ficheform.withWeight) {
            Ficheform.initWeightInput($$($entry, {ficheformRole: "cell-enumeration"}));
        }
        let $choices = $$($entry, {ficheformRole: "item-choices"});
        $$($choices, {ficheformRole: "item-choice"}).each(function (index, element) {
            __initChoice(element);
        });
        
        function __initChoice(choice) {
            let motcleId = choice.dataset.ficheformItemId;
            hereMap.set(parseInt(motcleId), true);
            let genId = Bdf.generateId();
            $$(choice, {_element: "label"}).after(Bdf.render("ficheform:include/choicebuttons", {
                genId: genId,
                noTab: Ficheform.getOption("noTab")
            }));
            Ficheform.initOrderButtons(genId, choice);
        }
        
        function __showEnumeration() {
            Ficheform.checkEnumerationCell(element, 1);
        }
        
        function __initSearchArea() {
            let searchInputId = Bdf.generateId();
            let searchAnchorId = Bdf.generateId();
            $$($entry, {ficheformRole: "searchcontainer"}).prepend(Bdf.render("ficheform:include/searcharea", {
                noTab: Ficheform.getOption("noTab"),
                createButtonId: "",
                searchInputId: searchInputId,
                withCreate: false,
                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) {
                        if (thesaurusInfo.isExternalSource) {
                           ___searchExternalSource(query);
                        } else {
                           ___searchThesaurus(query);
                        }
                    } else {
                        $$(searchAnchorId).html("");
                    }
                });
            });
            $$(searchAnchorId).on("click", $$.toCssSelector({action: "itemadd"}), function () {
                ___addChoice(thesaurusName, this.dataset.id);
                $$(searchAnchorId).html("");
                $$(searchInputId).val("");
                return false;
            });
            
            function ___addChoice(thesaurusName, id) {
                let requestParameters = {
                    properties: "special:phrases"
                };
                if (thesaurusInfo.isExternalSource) {
                    requestParameters.cmd = "MotcleCheck";
                }
                Bdf.api.loadMotcle({
                    thesaurus: thesaurusName,
                    id: id,
                    requestParameters: requestParameters,
                    callback: function (data) {
                        let motcle = data.motcle;
                        __showEnumeration();
                        let checkboxValue = id;
                        if (motcle.idalpha) {
                            checkboxValue = motcle.idalpha;
                        }
                        let title = Ficheform.concatMotcleTitle(motcle, thesaurusInfo.ficheform.idalphaStyle, true);
                        $choices.append(Bdf.render("ficheform:include/itemchoice", {
                            itemId: id,
                            checkboxName: entryKey,
                            checkboxValue: checkboxValue,
                            checkboxId: Bdf.generateId(),
                            withWeight: thesaurusInfo.ficheform.withWeight,
                            number: motcle.properties.number,
                            title: title
                        }));
                        __initChoice($$.one($choices, {ficheformItemId: id}));
                        Ficheform.signalChange();
                    }
                });
            }
            
            function ___searchExternalSource(query) {
                $.ajax({
                    url: Bdf.api.getActionUrl("pioche"),
                    method: "GET",
                    dataType: "json",
                    data: {
                        thesaurus: thesaurusName,
                        json: "externalitem",
                        q: query,
                        limit: 50,
                        sort: "id-desc"
                    },
                    success: function (data, textStatus) {
                        let externalArray = data.array;
                        if (externalArray.length === 0) {
                            ___updateSearch(Bdf.render("ficheform:include/searchinfo", {locKey: '_ info.edition.noresult'}));
                        } else {
                            let first = true;
                            for(let externalItem of externalArray) {
                                if (hereMap.has(externalItem.id)) {
                                    externalItem._here = true;
                                } else if (first) {
                                    externalItem._selected = first;
                                    first = false;
                                }
                                externalItem._title = externalItem.id + " – " + externalItem.title;
                            }
                            ___updateSearch(Bdf.render("ficheform:include/searchlist", {array: externalArray}));
                        }
                    }
                });
            }
            
            function ___searchThesaurus(query) {
                Bdf.api.loadMotcleArray({
                    motcleQuery: {
                        thesaurus: thesaurusName,
                        content: {
                            scope: Fql.SCOPE_IDALPHA_WITH,
                            q: query,
                            type: Fql.QTYPE_SIMPLE
                        },
                        status: "active"
                    },
                    requestParameters: {
                        limit: 50,
                        sortprecedence: _toSortPrecedence(query)
                    },
                    callback: function (data) {
                        let motcleArray = data.array;
                        if (motcleArray.length === 0) {
                            ___updateSearch(Bdf.render("ficheform:include/searchinfo", {locKey: '_ info.edition.noresult'}));
                        } else {
                            let first = true;
                            for(let motcle of motcleArray) {
                                if (hereMap.has(motcle.id)) {
                                    motcle._here = true;
                                } else if (first) {
                                    motcle._selected = first;
                                    first = false;
                                }
                                motcle._title = Ficheform.concatMotcleTitle(motcle, thesaurusInfo.ficheform.idalphaStyle);
                            }
                            ___updateSearch(Bdf.render("ficheform:include/searchlist", {array: motcleArray}));
                        }
                    }
                });
            }
            
            function ___updateSearch(html) {
                $$(searchAnchorId).removeClass("hidden").html(html);
            }

        }
    }
    
    function _toSortPrecedence(query) {
        let spaceIndex = query.indexOf(' ');
        if (spaceIndex > 0) {
            return query.substring(0, spaceIndex);
        } else {
            return query;
        }
    }
    
};

