<template>
    <CodeEditor ref="editor" :setup="setup" :value="value" @input="input" />
</template>

<script>
import { addClass } from 'uikit-util';
import { EditorView } from 'codemirror';
import { html } from '@codemirror/lang-html';
import { drawSelection, dropCursor, lineNumbers } from '@codemirror/view';
import { defaultHighlightStyle, syntaxHighlighting } from '@codemirror/language';
import { CodeEditor } from '../../../components';

import decorators from './decorators';

export default {
    name: 'ComposableSourceEditor',

    components: {
        CodeEditor,
    },

    props: {
        value: {
            type: String,
            required: true,
        },
        sources: {
            type: Object,
            required: true,
        },
        conditions: {
            type: Object,
            required: true,
        },
    },

    data: () => ({
        focused: false,
    }),

    computed: {
        setup() {
            const theme = EditorView.theme({
                '.cm-scroller': { overflow: 'auto', 'min-height': '100px', height: '200px' },
            });

            // const updateListener = EditorView.updateListener.of((update) => {
            //     this.focused = update.view.hasFocus;
            // });

            return [
                theme,
                // updateListener,
                html(),
                syntaxHighlighting(defaultHighlightStyle, { fallback: true }),
                lineNumbers(),
                drawSelection(),
                dropCursor(),
                // EditorView.lineWrapping,
                decorators({
                    vm: this,
                    sources: this.sources,
                    conditions: this.conditions,
                }),
            ];
        },
    },

    mounted() {
        addClass(
            this.$refs.editor.view.scrollDOM,
            'uk-textarea uk-padding-remove uk-resize-vertical'
        );
    },

    methods: {
        input(val) {
            this.$emit('input', val);
        },
    },
};
</script>
