/* global Bdf,$$,CodeMirror */

Bdf.CodeMirrorMode = {};

Bdf.CodeMirrorMode.visibilityListener = function (element, visible) {
    if (visible) {
        Bdf.refreshCodeMirror(element);
    }
};

Bdf.CodeMirrorMode.beforeSerialize = function (form) {
    $$(form, {_element: "textarea", codemirrorMode: true}).each(function (index, element) {
        let codeMirror = Bdf.getAssociatedCodeMirror(element);
        if (codeMirror) {
            codeMirror.save();
        }
    });
};

$(function () {
    if (Bdf.Deploy) {
        Bdf.Deploy.addVisibilityListener(Bdf.CodeMirrorMode.visibilityListener);
    }
    $$({_element: "textarea", codemirrorMode: true}).each(function (index, element) {
        let mode = element.dataset.codemirrorMode;
        let readOnly = false;
        let lineNumbers = false;
        let lineWrapping = true;
        let options = element.dataset.codemirrorOptions;
        if (options) {
            for(let option of options.split(" ")) {
                if (option === "numbers") {
                    lineNumbers = true;
                } else if (option === "nowrap") {
                    lineWrapping = false;
                }
            }
        }
        if (element.hasAttribute("disabled")) {
            readOnly = true;
        }
        if (mode) {
            if (mode === 'html') {
                mode = 'xml';
            }
            let codeMirror =  Bdf.toCodeMirror(element, {
                mode: mode,
                lineWrapping: lineWrapping,
                lineNumbers: lineNumbers,
                indentUnit: 4,
                readOnly: readOnly,
                theme: 'bdf',
                extraKeys: {
                    "Tab": false,
                    "Shift-Tab": false
                }
            });
        }
    });
});