/* global Bdf,$$,Access,Pane */

Access.Form = {};

Access.Form.load = function (accessName) {
    var access = Access.getAccess(accessName);
    if (!access) {
        return;
    }
    var isInStock = false;
    var formId = Bdf.generateId();
    $$("layout_main").html(Bdf.render("access:form", {
        action: Bdf.URL + "exportation",
        formId: formId,
        accessName: access.name,
        title: access.title,
        currentType: access.type,
        currentToken: access.token,
        labelArray: Bdf.toLabelArray(access.labelMap),
        labelsLocKey: "_ title.exportation.accesslabels",
        currentTableExportName : access.tableExportName,
        tableExportArray: Bdf.Collections.tableExportArray,
        selectionDefArray: Bdf.Collections.selectionDefArray,
        currentSelectionDefName: access.selectionDefName,
        queryXml: access.query.ficheXml + access.query.motcleXml,
        availableTargetArray: Bdf.pathConfiguration.targetArray,
        attributes: Bdf.attrMapToString(access.attrMap),
        attributesLocKey: "_ title.exportation.accessattributes",
        commandKey: "EXP-63",
        commandUrl: Bdf.getCommandUrl("EXP-63")
    }));
    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();
                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 newAccess = Access.updateAccess(data.access);
                    $$(formId, {role: "metadata-title"}).html(newAccess.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);
    }
    
};
