/* global Bdf,$$,SelectionDef,Pane */

SelectionDef.Form = {};

SelectionDef.Form.load = function (selectionDefName) {
    var selectionDef = SelectionDef.getSelectionDef(selectionDefName);
    if (!selectionDef) {
        return;
    }
    var isInStock = false;
    var formId = Bdf.generateId();
    $$("layout_main").html(Bdf.render("selectiondef:form", {
        action: Bdf.URL + "selection",
        formId: formId,
        selectionDefName: selectionDef.name,
        title: selectionDef.title,
        labelArray: Bdf.toLabelArray(selectionDef.labelMap),
        labelsLocKey: "_ title.selection.selectiondeflabels",
        queryXml: selectionDef.query.ficheXml + selectionDef.query.motcleXml,
        attributes: Bdf.attrMapToString(selectionDef.attrMap),
        attributesLocKey: "_ title.selection.selectiondefattributes",
        commandKey: "EXP-03",
        commandUrl: Bdf.getCommandUrl("EXP-03")
    }));
    Bdf.Deploy.init($$("layout_main"));
    $$(formId, "button_stock").click(function () {
        Pane.moveMainToStock();
    });
    $$(formId, "button_test").click(function () {
        SelectionDef.Overlay.showSelectionTest(selectionDefName);
    });
    $$(formId).ajaxForm({
        beforeSerialize: function ($form, options) {
            if (isInStock) {
                return false;
            } else {
                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 newSelectionDef = SelectionDef.updateSelectionDef(data.selectionDef);
                    $$(formId, {role: "metadata-title"}).html(newSelectionDef.title);
                }
            }
        }
    });
    var queryxmlCodeMirror = Pane.initQueryDetails(formId);
    var attributesCodeMirror = Pane.initAttributesDetails(formId);
    $$(formId).data("stockHandler", _stockHandler);
    Pane.checkState();
    Pane.checkTooltip($$(formId));
    
   
    function _stockHandler(stock) {
        isInStock = stock;
        queryxmlCodeMirror.setOption("readOnly", stock);
        attributesCodeMirror.setOption("readOnly", stock);
        Pane.setReadOnly($$(formId), stock);
    }
    
};
