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

TableExport.MetadataForm = {};

TableExport.MetadataForm.load = function (tableExportName) {
    var tableExport = TableExport.getTableExport(tableExportName);
    if (!tableExport) {
        return;
    }
    var isInStock = false;
    var formId = Bdf.generateId();
    var customLangs = "";
    if (tableExport.langArray) {
        customLangs = tableExport.langArray.join(';');
    }
    $$("layout_main").html(Bdf.render("tableexport:metadataform", {
        action: Bdf.URL + "exportation",
        formId: formId,
        tableExportName: tableExportName,
        title: tableExport.title,
        labelArray: Bdf.toLabelArray(tableExport.labelMap),
        labelsLocKey: "_ title.exportation.tableexportlabels",
        attributes: Bdf.attrMapToString(tableExport.attrMap),
        attributesLocKey: "_ title.exportation.tableexportattributes",
        langMode: {
            current: tableExport.langMode,
            customLangs: customLangs
        },
        commandKey: "EXP-13",
        commandUrl: Bdf.getCommandUrl("EXP-13")
    }));
    Bdf.Deploy.init($$("layout_main"));
    $$(formId, "button_stock").click(function () {
        Pane.moveMainToStock();
    });
    $$(formId).ajaxForm({
        beforeSerialize: function ($form, options) {
            if (isInStock) {
                return false;
            } else {
                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 newTableExport = TableExport.updateTableExport(data.tableExport);
                    $$(formId, {role: "metadata-title"}).html(newTableExport.title);
                }
            }
        }
    });
    var attributesCodeMirror = Pane.initAttributesDetails(formId);
    $$(formId).data("stockHandler", _stockHandler);
    Pane.checkState();
    Bdf.Shortcut.checkTooltip($$(formId));

    
    function _stockHandler(stock) {
        isInStock = stock;
        attributesCodeMirror.setOption("readOnly", stock);
        Pane.setReadOnly($$(formId), stock);
    }

};