<template>
    <div :class="[$style.quill,{[$style.error]: hasError}]">
        <div
            ref="textarea"
            class="notranslate quill-text">
        </div>
    </div>
</template>

<script>
import Quill from './quill';
import debounce from 'lodash.debounce';

export default {

    props: {
        contents: Object,
        hasError: Boolean,
    },

    data() {
        return {
            // uid: shortid.generate(),
            // active: false,
            // ready: false,
        };
    },

    //     watch: {
    //     contents(v) {
    //         this.quill.setContents(v);
    //     },
    // },

    mounted() {
        this.quill = new Quill(this.$refs.textarea, {
            modules: {
                toolbar: [
                    [{ header: [1, 2, false] }],
                    ['bold', 'italic', 'underline'],
                    [
                        { list: 'ordered' },
                        { list: 'bullet' },
                        { align: [] },
                    ],
                    ['link', 'image', 'video'],
                ],
            },
            placeholder: '',
            theme: 'snow',
        });

        if (this.contents) {
            this.quill.setContents(this.contents);
        }

        const onTextChange = debounce(this.onTextChange, 500);
        this.quill.on('text-change', onTextChange);

        document.body.addEventListener('click', this.close);
        document.body.addEventListener('quill-focus', (e) => {
            if (e.detail.id !== this.uid) {
                this.close();
            }
        });
        this.$once('hook:beforeDestroy', () => {
            document.body.removeEventListener('click', this.close);
        });
    },

    methods: {
        open() {
            this.active = true;
        },

        close() {
            this.active = false;
        },

        onTextAreaClick() {
            this.$el.dispatchEvent(
                new CustomEvent('quill-focus', {
                    bubbles: true,
                    detail: {
                        id: this.uid,
                    },
                }),
            );
        },

        onTextChange() {
            this.quill.update();
            this.$emit('change', this.quill.getContents());
        },
    },
};
</script>

<style module src="./QuillSimple.css" />
