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

Ficheform.ARGS = {
  noTab: false,
  syntaxActive: false,
  dateInputs: "iso",
  permissions: {
  },
  goto: ""
};
Ficheform.JsManagerInclude = ["_ @title_corpus@", "_ @title_thesaurus@", "_ @title_addenda@", "_ @corpus_newfiche@"];
Ficheform.hasChanges = false;
Ficheform.onSubmit = false;
Ficheform.timerMap = new Map();

Ficheform.init = function (goto) {
    $$({ficheformRole: "submit-button"}).prop("disabled", true);
    var $form = $$({ficheformRole: "form"}).on('submit', function () {
        Ficheform.onSubmit = true;
    });
    Bdf.addChangeTestFunction(function () {
        return Ficheform.hasChanges;
    });
    Bdf.initBeforeUnload({
        testFunction: function () {
            return (Ficheform.hasChanges) && (!Ficheform.onSubmit);
        }
    });
    Bdf.startTimer(function () {
        if (Ficheform.hasChanges) {
            return;
        }
        if (Bdf.checkFormChange($$({ficheformRole: "form"}))) {
            Ficheform.signalChange();
        }
    });
    if (!_goto()) {
        _seekFocus();
    }
    
    function _goto() {
        let done = false;
        if (goto) {
            let position = false;
            let idx = goto.indexOf("@");
            if (idx > 0) {
                position = goto.substring(idx + 1);
                goto = goto.substring(0, idx);
            }
            let target;
            try {
                target = $$.one({goto: goto});
            } catch (error) {
            }
            if (target) {
                let scrollDone = __scrollTop(target);
                if (position) {
                    let codeMirrorUnit = Ficheform.Section.codeMirrorUnitMap.get(target.dataset.ficheformKey);
                    if (codeMirrorUnit) {
                        done = true;
                        codeMirrorUnit.focusOnFicheBlock(position);
                    } else {
                        
                        let $input = $(target).find(__getInputSelector(target));
                        if ($input.length > 0) {
                            done = true;
                            let textArea = $input[0];
                            textArea.focus();
                            let lineRange = Ficheform.Section.getMatchingLineRange(textArea, position);
                            if (lineRange) {
                                textArea.setSelectionRange(lineRange[0], lineRange[1]);
                            }
                        }
                    }
                }
                if (!done) {
                    if (scrollDone) {
                        done = true;
                    }
                    let $input = $(target).find(__getInputSelector(target));
                    if ($input.length > 0) {
                        done = true;
                        $input[0].focus();
                    }
                }
            }
        }
        return done;
        
        function __scrollTop(target) {
            let viewport = Bdf.getMandatoryAncestor(target, {ficheformRole: "viewport"});
            if (viewport) {
                let top = $(target).position().top;
                $(viewport).scrollTop(top - 10);
                return true;
            } else {
                return false;
            }
        }
        
        function __getInputSelector(target) {
            if (target.dataset.ficheformEntry === "section") {
                return "textarea";
            } else {
                return "input:visible,select,textarea";
            }
        }
    }
    
    function _seekFocus() {
        for(let element of $form[0].elements) {
            let focusable = false;
            if (element instanceof HTMLInputElement) {
                switch(element.type) {
                    case "radio":
                    case "checkbox":
                    case "text":
                        focusable = true;

                }
            } else if (element instanceof HTMLSelectElement) {
                focusable = true;
            } else if (element instanceof HTMLTextAreaElement) {
                focusable = true;
            }
            if (focusable) {
                element.focus();
                break;
            }
        }
    }
};

Ficheform.getOption = function (name) {
    switch(name) {
        case "noTab":
            return Ficheform.ARGS.noTab;
        case "dateInputs":
            return Ficheform.ARGS.dateInputs;
        default:
            return false;
    }
};

/**
 * Retourne l'élément HTML correspondant à la clé
 * en argument.
 * 
 * @param {String} key Clé
 * @returns {JQuery} Objet JQuery correspondant
 */
Ficheform.entry = function (key) {
    return $$.one({ficheformRole: "entry", ficheformKey: key});
};

Ficheform.signalChange = function () {
    if (!Ficheform.hasChanges) {
        Ficheform.hasChanges = true;
        $$({ficheformRole: "submit-button"}).prop("disabled", false);
        Bdf.clearTimer();
    }
};

Ficheform.getWeightString = function (value) {
    var idx = value.indexOf("<");
    if (idx === -1) return "";
    return value.substring(idx);
};

Ficheform.getWeight = function (value) {
    var idx = value.indexOf("<");
    if (idx === -1) return "";
    var weight = value.substring(idx+1, value.length -1);
    return weight;
};

Ficheform.checkWeight = function (value) {
    value = value.trim();
    if (value.length === 0) return 1;
    if (_is_int()) {
        if (value > 0) return value;
        else return false;
    }
    else return false;
    
    
    function _is_int(){
        if((parseFloat(value) == parseInt(value)) && !isNaN(parseInt(value))) {
            return true;
        } else {
            return false;
        }
    }
};

Ficheform.updateCheckBox = function (checkBox, weight) {
    var currentValue = checkBox.value;
    var idx = currentValue.indexOf("<");
    if (idx > -1) {
        currentValue = currentValue.substring(0, idx);
    }
    if (weight > 1) {
        checkBox.value = currentValue + "<" + weight + ">";
    } else  {
        checkBox.value = currentValue;
    }
};

Ficheform.openDialog = function (dialogUrl, dialogName, width, height) {
    var w = window.open(dialogUrl,dialogName,"resizable=yes,width=" + width + ",height=" + height + ",scrollbars");
    w.focus();
};

Ficheform.removeFromValue = function(value, id, separator) {
    var idString = String(id);
    var array = value.split(";");
    var newVal = "";
    for(let token of array) {
        if (separator) {
            let idx = token.indexOf(separator);
            if (idx > 0) {
                let tokenId = token.substring(0, idx);
                if (tokenId !== idString) {
                    newVal += token + ";";
                }
            }
        } else {
            if (token !== idString) {
                newVal += token + ";";
            }
        }
    }
    return newVal;
};

Ficheform.initWeightInput = function ($itemList) {
    let buttonId = Bdf.generateId();
    $itemList.append(Bdf.render("bdf:button-transparent32", {
        buttonId: buttonId,
        action: "action-ficheform-Weight_on",
        locKey: "_ link.edition.weight_on",
        noTab: Ficheform.getOption("noTab")
    }));
    $$(buttonId).data("state", "on").click(function () {
       let $this = $(this);
       if ($this.data("state") === "on") {
           $this.removeClass("action-ficheform-Weight_on").addClass("action-ficheform-Weight_off");
           $this.attr("title", Bdf.Loc.get("_ link.edition.weight_off"));
           $this.data("state", "off");
           _display();
       } else {
           $this.removeClass("action-ficheform-Weight_off").addClass("action-ficheform-Weight_on");
           $this.attr("title", Bdf.Loc.get("_ link.edition.weight_on"));
           $this.data("state", "on");
           _save();
       }
    });
        
    function _display() {
        $$($itemList, {ficheformRole: "item-choice"}).each(function (index, element) {
            let $checkbox = $$(element, {ficheformRole: "item-checkbox"});
            let weight = Ficheform.getWeight($checkbox[0].value);
            $checkbox.after(Bdf.render("ficheform:weightinput", {
                weight: weight
            }));
        });
        $$($itemList, {ficheformRole: "weight"}).hide();
    }

    function _save() {
        $$($itemList, {ficheformRole: "item-choice"}).each(function (index, element) {
            let weightInput = $$.one(element, {ficheformRole: "weight-input"});
            let value = weightInput.value;
            let checkBox = $$.one(element, {ficheformRole: "item-checkbox"});
            if (Ficheform.checkWeight(value)) {
                Ficheform.updateCheckBox(checkBox, value);
            }
            $(weightInput).remove();
            $$(element, {ficheformRole: "weight"}).text(Ficheform.getWeightString(checkBox.value)).show();
        });
        Ficheform.signalChange();
    }
};

Ficheform.getCurrentCorpus = function (element) {
    if (!element) {
        let $form = $$({ficheformRole: "form"});
        if ($form.length === 0) {
            return "";
        } else {
            return $form[0].dataset.ficheformCorpus;
        }
    } else if (element.dataset.ficheformCorpus) {
        return element.dataset.ficheformCorpus;
    } else {
        return Bdf.getMandatoryAncestor(element, {ficheformRole: "form"}).dataset.ficheformCorpus;
    }
};

Ficheform.initOrderButtons = function (rootId, element, callback) {
    $$(rootId, "up").click(function () {
        let $previous = $(element).prev();
        if ($previous.length > 0) {
            $previous.before(element);
            Ficheform.signalChange();
            if (callback) {
                callback("up");
            }
        }
    });
    $$(rootId, "down").click(function () {
        let $next = $(element).next();
        if ($next.length > 0) {
            $next.after(element);
            Ficheform.signalChange();
            if (callback) {
                callback("down");
            }
        }
    });
};

Ficheform.initSearchInput = function (searchInputId, searchAnchorId, searchFunction) {
    $$(searchInputId).on("input", function (inputEvent) {
            searchFunction(this, inputEvent);
        }).on('keydown', function (keyEvent) {
            switch(keyEvent.key) {
                case "Enter": {
                    _getSelected().find("a").click();
                    keyEvent.stopPropagation();
                    keyEvent.preventDefault();
                    break;
                }
                case "ArrowDown": {
                    let $selected = _getSelected();
                    let $nextAll = $selected.nextAll($$.toCssSelector({ficheformRole: "candidate"}));
                    if ($nextAll.length > 0) {
                        $selected.removeClass("ficheform-search-Selected");
                        _select($nextAll[0]);
                    }
                    keyEvent.preventDefault();
                    break;
                }
                case "ArrowUp": {
                    let $selected = _getSelected();
                    let $previousAll = $selected.prevAll($$.toCssSelector({ficheformRole: "candidate"}));
                    if ($previousAll.length > 0) {
                        $selected.removeClass("ficheform-search-Selected");
                        _select($previousAll[0]);
                    }
                    keyEvent.preventDefault();
                    break;
                }
            }
        }).on("blur", function () {
            setTimeout(function () {$$(searchAnchorId).addClass("hidden");}, 250);
        }).on("focus", function () {
            $$(searchAnchorId).removeClass("hidden");
        }).attr("autocomplete", "off");
    
    function _getSelected() {
        return $$(searchAnchorId).find(".ficheform-search-Selected");
    }
    
    function _select(element) {
        element.classList.add("ficheform-search-Selected");
        Bdf.ensureVisibility(Bdf.getMandatoryAncestor(element, {ficheformRole:"search-popup"}), element);
    }
};

Ficheform.checkEnumerationCell = function (entry, size) {
    var $enumerationCell = $$(entry, {ficheformRole: "cell-enumeration"});
    if (size > 0) {
        $enumerationCell.removeClass("hidden");
    } else {
        $enumerationCell.addClass("hidden");
    }
};

Ficheform.delayFunction = function (id, delayedFunction) {
    clearTimeout(Ficheform.timerMap.get(id));
    let newTimer = setTimeout(delayedFunction, 300);
    Ficheform.timerMap.set(id, newTimer);
};

Ficheform.concatMotcleTitle = function (motcle, idalphaStyle, onlySignificant) {
    var idalpha = motcle.idalpha;
    var title = motcle.title;
    if (!idalpha) {
        return title;
    }
    if ((onlySignificant) && (idalpha.indexOf('_') === 0)) {
        return title;
    }
    if (idalphaStyle === "ignore") {
        return title;
    }
    if (idalphaStyle === "brackets") {
        let text = "[" + idalpha + "]";
        if (title) {
            text += " " + title;
        }
        return text;
    }
    let text = idalpha;
    if (title) {
        text += " – " + title;
    }
    return text;
};
