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

TableExport.ContentForm = {};

TableExport.ContentForm.load = function (tableExportContent, isInStock) {
    if (!isInStock) {
        isInStock = false;
    }
    var tableExportName = tableExportContent.tableExportName;
    var contentPath = tableExportContent.path;
    var subsetKeyObj = TableExport.parseSubsetKey(contentPath);
    var content = tableExportContent.content;
    var readOnly = !(tableExportContent.editable);
    var formId = Bdf.generateId();
    var textareaId = formId + "_content";
    var htmlContent = Bdf.render("tableexport:contentform", {
        action: Bdf.URL + "exportation",
        formId: formId,
        tableExportName: tableExportName,
        path: contentPath,
        content: content,
        title: _getTitle(),
        subsetKey: subsetKeyObj.subsetKey,
        subsetCategory: subsetKeyObj.subsetCategory,
        subsetName: subsetKeyObj.subsetName
    });
    if (isInStock) {
        Pane.addStockUnit(htmlContent);
    } else {
        $$("layout_main").html(htmlContent);
    }
    $$(formId, "button_delete").click(function () {
        TableExport.Overlay.showContentRemoveConfirm(tableExportName, contentPath);
    });
    $$(formId, "button_test").click(function () {
        TableExport.Overlay.showTableTest(tableExportName, contentPath);
    });
    $$(formId, "button_stock").click(function () {
        Pane.moveMainToStock();
    });
    $$(formId).ajaxForm({
        beforeSerialize: function ($form, options) {
            if (isInStock) {
                return false;
            } else {
                codeMirror.save();
                return true;
            }
        },
        dataType: "json",
        success: function (data, textStatus, jqXHR, $form) {
            if (Bdf.checkError(data)) {
                Pane.setChange(false);
                Bdf.showCommandMessage(data.commandMessage);
                TableExport.List.updateTableExport(data.tableExport);
            }
        }
    });
    var codeMirror = Bdf.toCodeMirror(textareaId, {
        lineWrapping: false,
        lineNumbers: true,
        indentUnit: 4,
        mode: "tableexport",
        theme: 'bdf',
        readOnly: readOnly
    });
    $$(textareaId).prop("disabled", readOnly);
    codeMirror.on("change", function () {
        Pane.setChange(true);
    });
    $$(formId).data("stockHandler", _stockHandler);
    Pane.checkState();
    Pane.checkTooltip($$(formId));

    function _getTitle() {
        let subset = TableExport.subsetTrees.getSubset(subsetKeyObj.subsetKey);
        if (subset) {
            return subset.title;
        } else {
            return "";
        }
    }
    
    function _stockHandler(stock) {
        isInStock = stock;
        codeMirror.setOption("readOnly", stock);
    }
    
};