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

Balayage.MetadataForm = {};

Balayage.MetadataForm.load = function (balayageName) {
    var balayage = Balayage.getBalayage(balayageName);
    if (!balayage) {
        return;
    }
    var isInStock = false;
    var formId = Bdf.generateId();
    $$("layout_main").html(Bdf.render("balayage:metadataform", {
        action: Bdf.URL + "exportation",
        formId: formId,
        balayageName: balayageName,
        title: balayage.title,
        labelArray: Bdf.toLabelArray(balayage.labelMap),
        labelsLocKey: "_ title.exportation.balayagelabels",
        langs: balayage.langs.join(";"),
        selectionDefArray: Bdf.Collections.selectionDefArray,
        currentSelectionDefName: balayage.selectionDefName,
        postcriptumArray: _getPostcriptumArray(),
        unitsXml: _mergeUnits(),
        queryXml: balayage.query.ficheXml + balayage.query.motcleXml,
        targetName: balayage.targetName,
        targetPath: balayage.targetPath,
        langOptions: Balayage.getLangOptions(balayage.defaultLangOption),
        ignoreTransformation: balayage.ignoreTransformation,
        targetOptionArray: _getTargetOptions(balayage.targetName),
        attributes: Bdf.attrMapToString(balayage.attrMap),
        attributesLocKey: "_ title.exportation.balayageattributes",
        commandKey: "EXP-53",
        commandUrl: Bdf.getCommandUrl("EXP-53")
    }));
    Bdf.Deploy.init($$("layout_main"));
    $$(formId, "button_stock").click(function () {
        Pane.moveMainToStock();
    });
    $$(formId).ajaxForm({
        beforeSerialize: function ($form, options) {
            if (isInStock) {
                return false;
            } else {
                queryxmlCodeMirror.save();
                attributesCodeMirror.save();
                unitsxmlCodeMirror.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 newBalayage = Balayage.updateBalayage(data.balayage);
                    $$(formId, {role: "metadata-title"}).html(newBalayage.title);
                }
            }
        }
    });
    var queryxmlCodeMirror = Pane.initQueryDetails(formId);
    var attributesCodeMirror = Pane.initAttributesDetails(formId);
    var unitsxmlCodeMirror = Bdf.toCodeMirror($$.one(formId, "unitsxml"), {
        lineWrapping: false,
        lineNumbers: false,
        indentUnit: 4,
        theme: 'bdf',
        mode: "xml"
    });
    unitsxmlCodeMirror.on("change", function () {
        Pane.setChange(true);
    });
    $$(formId, "button_addbalayageunit").click(function () {
        Balayage.Overlay.showAddBalayageUnit(function (xml) {
            let unitsDoc = unitsxmlCodeMirror.getDoc();
            let lineCount = unitsDoc.lineCount();
            unitsDoc.replaceRange("\n" + xml, {line: lineCount, ch: 0});
        });
    });
    $$(formId).data("stockHandler", _stockHandler);
    Pane.checkState();
    Bdf.Shortcut.checkTooltip($$(formId));

    
    function _stockHandler(stock) {
        isInStock = stock;
        queryxmlCodeMirror.setOption("readOnly", stock);
        attributesCodeMirror.setOption("readOnly", stock);
        unitsxmlCodeMirror.setOption("readOnly", stock);
        Pane.setReadOnly($$(formId), stock);
    }
    
    function _mergeUnits() {
        let xml = "";
        for(let unit of balayage.units) {
            if (xml.length > 0) {
                xml += "\n";
            }
            xml += unit.xml;
        }
        return xml;
    }
    
    function _getPostcriptumArray() {
        let postcriptumArray = new Array();
        if (Bdf.Collections.externalScriptArray.length > 0) {
            postcriptumArray.push({
               titleKey: "_ title.configuration.scripts",
               checkboxArray: __getCheckboxArray(Bdf.Collections.externalScriptArray, "script")
            });
        }
        if (Bdf.Collections.scrutariExportArray.length > 0) {
            postcriptumArray.push({
               titleKey: "_ label.exportation.scrutariexports",
               checkboxArray: __getCheckboxArray(Bdf.Collections.scrutariExportArray, "scrutari")
            });
        }
        if (Bdf.Collections.sqlExportArray.length > 0) {
            postcriptumArray.push({
               titleKey: "_ label.exportation.sqlexports",
               checkboxArray: __getCheckboxArray(Bdf.Collections.sqlExportArray, "sql")
            });
        }
        return postcriptumArray;
        
        function __getCheckboxArray(availableArray, name, ) {
            let existingArray = balayage.postscriptum[name];
            let checkboxArray = new Array();
            for(let obj of availableArray) {
                let value = obj.name;
                let title = obj.title;
                let label = "";
                if (title) {
                    label = "[" + value + "]" + " " + title;
                } else {
                    label = value;
                }
                let checked = false;
                if (existingArray.indexOf(value) !== -1) {
                    checked = true;
                }
                checkboxArray.push({
                    name: name,
                    id: formId + "_postscriptum_" + name + "_" + value,
                    value: value,
                    label: label,
                    checked: checked
                });
            }
            return checkboxArray;        
        }
    }
    
    function _getTargetOptions(currentTargetName) {
        let array = new Array();
        let done = false;
        if (currentTargetName === '_public') {
            done = true;
        }
        array.push({
            value: "_public",
            label: Bdf.Loc.get('_ label.configuration.publicpath'),
            selected: (currentTargetName === '_public')
        });
        for(let target of Bdf.pathConfiguration.targetArray) {
            let selected = (target === currentTargetName);
            if (selected) {
                done = true;
            }
            array.push({
                value: target,
                label: target,
                selected: selected
            });
        }
        if ((!done) && (currentTargetName)) {
            array.push({
                value: currentTargetName,
                label: "?" + currentTargetName + "?",
                selected: true
            });
        }
        return array;
    }
    

};