<template>
  <textarea ref="textarea"></textarea>
</template>

<script>
import CodeMirror from 'codemirror';
import 'codemirror/lib/codemirror.css';
import 'codemirror/theme/rubyblue.css';
import 'codemirror/mode/javascript/javascript';
import 'codemirror/addon/fold/foldcode.js';
import 'codemirror/addon/fold/foldgutter.js';
import 'codemirror/addon/fold/brace-fold.js';
import 'codemirror/addon/fold/foldgutter.css';

export default {
    data () {
        return {
        };
    },
    props: ['value'],
    watch: {
        value: {
            handler (value) {
                const editorValue = this.jsonView.getValue();
                if (value !== editorValue) {
                    this.jsonView.setValue(JSON.stringify(this.value, null, 2));
                }
            },
            deep: true
        }
    },
    mounted () {
        this.jsonView = CodeMirror.fromTextArea(this.$refs.textarea, {
            lineNumbers: true,
            mode: 'application/json',
            lineWrapping: true,
            foldGutter: true,
            gutters: ['CodeMirror-linenumbers', 'CodeMirror-foldgutter'],
            theme: 'rubyblue',
            readOnly: true
        });

        this.jsonView.setValue(JSON.stringify(this.value, null, 2));
        this.jsonView.on('change', cm => {
            this.$emit('changed', cm.getValue());
            this.$emit('input', cm.getValue());
        });
    },
    methods: {
        getValue () {
            return this.jsonView.getValue();
        }
    }
};
</script>
