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

Transformation.MetadataForm = {};

Transformation.MetadataForm.load = function (templateKey) {
    var templateDescription = Transformation.getTemplateDescription(templateKey);
    if (!templateDescription) {
        return;
    }
    var isInStock = false;
    var formId = Bdf.generateId();
    $$("layout_main").html(Bdf.render("transformation:metadataform", {
        action: Bdf.URL + "exportation",
        formId: formId,
        templateKey: templateKey,
        split: Transformation.split(templateKey),
        title: templateDescription.title,
        labelArray: Bdf.toLabelArray(templateDescription.labelMap),
        labelsLocKey: "_ title.exportation.templatelabels",
        attributes: Bdf.attrMapToString(templateDescription.attrMap),
        attributesLocKey: "_ title.exportation.templateattributes",
        commandKey: "EXP-33",
        commandUrl: Bdf.getCommandUrl("EXP-33")
    }));
    $$(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 newtemplateDescription = Transformation.updateTemplateDescription(data.templateDescription);
                    $$(formId, {role: "metadata-title"}).html(newtemplateDescription.title);
                }
            }
        }
    });
    var attributesCodeMirror = Pane.initAttributesDetails(formId);
    $$(formId).data("stockHandler", _stockHandler);
    Pane.checkState();
    Pane.checkTooltip($$(formId));

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