/* global Bdf,$$,ScrutariExport,CodeMirror,Pane */

ScrutariExport.Form = {};

ScrutariExport.Form.load = function (scrutariExportName) {
    var scrutariExport = ScrutariExport.getScrutariExport(scrutariExportName);
    if (!scrutariExport) {
        return;
    }
    var isInStock = false;
    var formId = Bdf.generateId();
    $$("layout_main").html(Bdf.render("scrutariexport:form", {
        action: Bdf.URL + "exportation",
        formId: formId,
        scrutariExportName: scrutariExport.name,
        title: scrutariExport.title,
        labelArray: Bdf.toLabelArray(scrutariExport.labelMap),
        labelsLocKey: "_ title.exportation.scrutariexportlabels",
        authority: scrutariExport.authority,
        baseName: scrutariExport.baseName,
        baseIcon: scrutariExport.baseIcon,
        ficheHrefPattern: scrutariExport.ficheHrefPattern,
        motcleHrefPattern: scrutariExport.motcleHrefPattern,
        langsUi: scrutariExport.langUiArray.join(";"),
        shortTitles: _toTitles("short"),
        longTitles: _toTitles("long"),
        includeTokens: scrutariExport.includeTokenArray.join(";"),
        corpusTree: ScrutariExport.Form.toCorpusTree(scrutariExport.corpusScrutariArray),
        thesaurusTree: ScrutariExport.Form.toThesaurusTree(scrutariExport.thesaurusScrutariArray),
        selectionDefArray: Bdf.Collections.selectionDefArray,
        currentSelectionDefName: scrutariExport.selectionDefName,
        queryXml: scrutariExport.query.ficheXml + scrutariExport.query.motcleXml,
        targetName: scrutariExport.targetName,
        targetPath: scrutariExport.targetPath,
        availableTargetArray: Bdf.pathConfiguration.targetArray,
        attributes: Bdf.attrMapToString(scrutariExport.attrMap),
        attributesLocKey: "_ title.exportation.scrutariexportattributes",
        commandKey: "EXP-23",
        commandUrl: Bdf.getCommandUrl("EXP-23")
    }));
    Bdf.Deploy.init($$("layout_main"));
    $$(formId, "button_stock").click(function () {
        Pane.moveMainToStock();
    });
    
    $$(formId).ajaxForm({
        beforeSerialize: function ($form, options) {
            if (isInStock) {
                return false;
            } else {
                for(let codeMirror of fieldFormatCodeMirrorArray) {
                    codeMirror.save();
                }
                queryxmlCodeMirror.save();
                attributesCodeMirror.save();
                return true;
            }
        },
        dataType: "json",
        success: function (data, textStatus, jqXHR, $form) {
            if (Bdf.checkError(data)) {
                Pane.setChange(false);
                if (Bdf.showCommandMessage(data.commandMessage)) {
                    Bdf.updateDefaultValues($$(formId));
                    let newScrutariExport = ScrutariExport.updateScrutariExport(data.scrutariExport);
                    $$(formId, {role: "metadata-title"}).html(newScrutariExport.title);
                }
                ScrutariExport.Form.checkLog(data);
            }
        }
    });
    var fieldFormatCodeMirrorArray = new Array();
    $$(formId).find("textarea[name$='\\|fieldgenerationsource']").each(function (index, element) {
        let codeMirror = Bdf.toCodeMirror(element, {
            lineWrapping: false,
            lineNumbers: true,
            indentUnit: 4,
            theme: 'bdf',
            mode: "tableexport"
        });
        codeMirror.on("change", function () {
            Pane.setChange(true);
        });
        fieldFormatCodeMirrorArray.push(codeMirror);
    });
    var queryxmlCodeMirror = Pane.initQueryDetails(formId);
    var attributesCodeMirror = Pane.initAttributesDetails(formId);
    $$(formId).data("stockHandler", _stockHandler);
    Pane.checkState();
    Pane.checkTooltip($$(formId));
    
    function _toTitles(key) {
        if (!scrutariExport.baseIntituleMap.hasOwnProperty(key)) {
            return "";
        }
        var intitule = scrutariExport.baseIntituleMap[key];
        var text = "";
        for(let prop in intitule) {
            text += prop;
            text += "=";
            text += intitule[prop];
            text += "\n";
        }
        return text;
    }
    
    function _stockHandler(stock) {
        isInStock = stock;
        for(let codeMirror of fieldFormatCodeMirrorArray) {
            codeMirror.setOption("readOnly", stock);
        }
        queryxmlCodeMirror.setOption("readOnly", stock);
        attributesCodeMirror.setOption("readOnly", stock);
        Pane.setReadOnly($$(formId), stock);
    }
    
};

ScrutariExport.Form.toCorpusTree = function (corpusScrutariArray) {
    var corpusMap = new Object(); 
    for(let corpusScrutari of corpusScrutariArray) {
        corpusMap[corpusScrutari.subsetName] = corpusScrutari;
    }
    return _readNodeArray(ScrutariExport.subsetTrees.getTree("corpus"));
    
    function _readNodeArray(nodeArray) {
        var resultArray = new Array();
        for(let node of nodeArray) {
            let resultItem = {
                node:  node.node,
                name: node.name,
                title: node.title,
                generatedId: Bdf.generateId() 
            };
            if (node.node === "subset") {
                let subsetName = node.name;
                resultItem.subsetKey = "corpus_" + subsetName;
                resultItem.subsetName = subsetName;
                resultItem.subsetCategory = "corpus";
                let checked = false;
                let corpusScrutari;
                if (corpusMap.hasOwnProperty(subsetName)) {
                    checked = true;
                    corpusScrutari = corpusMap[subsetName];
                } else {
                    corpusScrutari = {
                        hrefPattern: "",
                        fieldGenerationSource: "",
                        dateSource: "",
                        multilangMode: "",
                        multilangParam: "",
                        includeTokenArray: []
                    };
                }
                resultItem.checked = checked;
                resultItem.corpusScrutari = corpusScrutari;
                resultItem.withoutDateSource = (corpusScrutari.dateSource.length === 0);
                resultItem.dateSourceArray = _toDateSourceArray(node, corpusScrutari.dateSource);
                resultItem.isMultilang = (corpusScrutari.multilangMode.length > 0);
                resultItem.multilangMode = corpusScrutari.multilangMode;
                resultItem.multilang = _toMultilang(node, corpusScrutari);
                resultItem.includeTokens = corpusScrutari.includeTokenArray.join(";");
            } else if (node.node === "group") {
                resultItem.hidden = !_testGroup(node);
                resultItem.items =  _readNodeArray(node.array);
            }
            resultArray.push(resultItem);
        }
        return resultArray;
    }
    
    function _toMultilang(corpusNode, corpusScrutari) {
        var mode = corpusScrutari.multilangMode;
        var hidden = false;
        if (!mode) {
            hidden = true;
        }
        var multilang = {
            mode: mode,
            hidden: hidden,
            isLangUi: ((mode === "langui") || hidden),
            isThesaurus: (mode === "thesaurus"),
            isField: (mode === "field"),
            isCustom: (mode === "custom"),
            customValue: ""
        };
        if (multilang.isCustom) {
            multilang.customValue = corpusScrutari.multilangParam;
        }
        var thesaurusOptions = new Array();
        var currentValue = "";
        if (multilang.isThesaurus) {
            currentValue = corpusScrutari.multilangParam;
        }
        _appendToMultilangOptions(ScrutariExport.subsetTrees.getTree("thesaurus"), thesaurusOptions, currentValue);
        var hasSelection = false;
        for (let thesaurusOption of thesaurusOptions) {
            if (thesaurusOption.selected) {
                hasSelection = true;
                break;
            }
        }
        if ((!hasSelection) && (thesaurusOptions.length > 0)) {
            thesaurusOptions[0].selected = true;
        }
        multilang.thesaurusOptions = thesaurusOptions;
        if (multilang.isField) {
            currentValue = corpusScrutari.multilangParam;
        } else {
            currentValue = "";
        }
        var availableFieldArray = _getAvailableFieldArray(corpusNode, "language");
        var fieldOptions = new Array();
        var hasLangSelected = false;
        for(let detail of availableFieldArray) {
           let selected = false;
           if (detail.key === currentValue) {
               selected = true;
               hasLangSelected = true;
           }
           let item = {
               name: detail.key,
               title: detail.title,
               selected: selected
           };
           fieldOptions.push(item);
        }
        if ((!hasLangSelected) && (fieldOptions.length > 0)) {
            fieldOptions[fieldOptions.length -1].selected = true;
        }
        multilang.fieldOptions = fieldOptions;
        return multilang;
    }
    
    function _toDateSourceArray(node, currentDateSource) {
        var result = new Array();
        var availableFieldArray = _getAvailableFieldArray(node, "date");
        for(let detail of availableFieldArray) {
           let item = {
               name: detail.key,
               title: detail.title,
               selected: (detail.key === currentDateSource)
           };
           result.push(item);
        }
        return result;
    }
    
    
    function _testGroup(groupNode) {
        for(let node of groupNode.array) {
            if (node.node === "subset") {
                if (corpusMap.hasOwnProperty(node.name)) {
                    return true;
                }
            } else if (node.node === "group") {
                let subgroupResult = _testGroup(node);
                if (subgroupResult) {
                    return true;
                }
            }
        }
        return false;
    }
    
    function _appendToMultilangOptions(nodeArray, optionArray, currentValue) {
        for(let node of nodeArray) {
            if (node.node === "subset") {
                let item = {
                    name: node.name,
                    title: node.title,
                    selected: (node.name === currentValue)
                };
                optionArray.push(item);
            } else if (node.node === "group") {
                _appendToMultilangOptions(node.array, optionArray, currentValue);
            }
        }
    }
    
    function _getAvailableFieldArray(subsetNode, patternType) {
        var result = new Array();
        __pushDetails(subsetNode.details.misc);
        __pushDetails(subsetNode.details.ui);
        return result;


        function __pushDetails(detailArray) {
            if (detailArray) {
                for(let detail of detailArray) {
                    if (detail.patternType === patternType) {
                        result.push(detail);
                    }
                }
            }
        }
    }
    
};

ScrutariExport.Form.toThesaurusTree = function (thesaurusScrutariArray) {
    var thesaurusMap = new Object(); 
    for(let thesaurusScrutari of thesaurusScrutariArray) {
        thesaurusMap[thesaurusScrutari.subsetName] = thesaurusScrutari;
    }
    return _readNodeArray(ScrutariExport.subsetTrees.getTree("thesaurus"));


    function _readNodeArray(nodeArray) {
        var resultArray = new Array();
        for(let node of nodeArray) {
            let resultItem = {
                node:  node.node,
                name: node.name,
                title: node.title,
                generatedId: Bdf.generateId() 
            };
            if (node.node === "subset") {
                let subsetName = node.name;
                resultItem.subsetKey = "thesaurus_" + subsetName;
                resultItem.subsetName = subsetName;
                resultItem.subsetCategory = "thesaurus";
                let checked = false;
                let thesaurusScrutari;
                if (thesaurusMap.hasOwnProperty(subsetName)) {
                    checked = true;
                    thesaurusScrutari = thesaurusMap[subsetName];
                } else {
                    thesaurusScrutari = {
                        fieldGenerationSource: "",
                        wholeThesaurus: false,
                        includeTokenArray: []
                    };
                }
                resultItem.checked = checked;
                resultItem.isWholeThesaurus = thesaurusScrutari.wholeThesaurus;
                resultItem.includeTokens = thesaurusScrutari.includeTokenArray.join(";");
                resultItem.thesaurusScrutari = thesaurusScrutari;
            } else if (node.node === "group") {
                resultItem.hidden = !_testGroup(node);
                resultItem.items =  _readNodeArray(node.array);
            }
            resultArray.push(resultItem);
        }
        return resultArray;
    }
    
    function _testGroup(groupNode) {
        for(let node of groupNode.array) {
            if (node.node === "subset") {
                if (thesaurusMap.hasOwnProperty(node.name)) {
                    return true;
                }
            } else if (node.node === "group") {
                let subgroupResult = _testGroup(node);
                if (subgroupResult) {
                    return true;
                }
            }
        }
        return false;
    }

};

ScrutariExport.Form.checkLog = function (data) {
    $$({role: "log"}).html("").addClass("hidden");
    if (data.lineLogsMap) {
        var alertMessage = Bdf.Loc.get("_ warning.exportation.fieldgenerationerrors") + "\n";
         for(let subsetKey in data.lineLogsMap) {
             alertMessage += "\n- [" + subsetKey + "]";
             let subset = ScrutariExport.subsetTrees.getSubset(subsetKey);
             if (subset) {
                 alertMessage += " – " + subset.title;
             }
             $$({role: "log", subset: subsetKey}).html(Bdf.render("bdf:linelogarray", {lineLogArray: data.lineLogsMap[subsetKey]})).removeClass("hidden");
         }
         alert(alertMessage);
    }
};
