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

Resource.Form = {};

Resource.Form.load = function (streamText, isInStock) {
    if (!isInStock) {
        isInStock = false;
    }
    var path = streamText.path;
    var origins = $$.one({role: "content-reference", path: path}).dataset.origins;
    var extension = streamText.extension;
    var content = streamText.content;
    var deleteKey = "_ link.resource.restore";
    if (origins === "var") {
        deleteKey = "_ link.global.delete";
    }
    var formId = Bdf.generateId();
    var textareaId = formId + "_content";
    var deleteId = formId + "_button_delete";
    var htmlContent = Bdf.render("resource:form", {
        action: Bdf.URL + "administration",
        formId: formId,
        path: path,
        content: content,
        deleteKey: deleteKey,
        deleteEnable: (origins.indexOf("var") > - 1)
    });
    if (isInStock) {
        Pane.addStockUnit(htmlContent);
    } else {
        $$("layout_main").html(htmlContent);
    }
    $$(deleteId).click(function () {
        Resource.Overlay.showRemoveConfirm(path, (origins === "var"));
    });
    $$(formId, "button_stock").click(function () {
        Pane.moveMainToStock();
    });
    var mode = Bdf.getMatchingCodeMirrorMode(extension);
    var options = {
        theme: 'bdf',
        lineWrapping: false,
        lineNumbers: true,
        indentUnit: 4,
        mode: mode
    };
    $$(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);
                Resource.List.update();
                Bdf.showCommandMessage(data.commandMessage);
                _setDeleteEnable(true);
            }
        }
    });
    var codeMirror = Bdf.toCodeMirror(textareaId, options);
    codeMirror.on("change", function () {
        Pane.setChange(true);
    });
    $$(formId).data("stockHandler", _stockHandler);
    Pane.checkState();
    Pane.checkTooltip($$(formId));

    
    function _setDeleteEnable(enable) {
        if (enable) {
            $$(deleteId).data("stateEnable", "!change-current");
            $$(deleteId).prop("disabled", false);
        } else {
            $$(deleteId).prop("disabled", true);
        }
    }
    
    function _stockHandler(stock) {
        isInStock = stock;
        codeMirror.setOption("readOnly", stock);
    }
    
};