<template>
    <div class="bgo-rich-text">
        <textarea ref="editor" style="width: 100%;"></textarea>
    </div>
</template>

<script>
import katex from "katex";
import suneditor from "suneditor";
import plugins from "suneditor/src/plugins";
import {zh_cn} from "suneditor/src/lang";

import defaultButtonList from "./button-list";

import "suneditor/dist/css/suneditor.min.css";
import 'katex/dist/katex.min.css';

import "./index.scss";

export default {
    name: "BgoRichText",
    props: {
        value: {
            type: String,
            default: "",
        },
        readonly: {
            type: Boolean,
            default: false,
        },
        disable: {
            type: Boolean,
            default: false,
        },
        editorOptions: {
            type: Object,
            default: () => {},
        }
    },
    data() {
        // suneditor instance
        this._editor = null;
        return {};
    },
    watch: {
        value(newContent) {
            this._setContents(newContent);
        },
        readonly(isReadonly) {
            if (this._editor) {
                this._editor.readOnly(isReadonly);
            }
        },
        disable(disable) {
            this._setDisable(disable);
        },
    },
    mounted() {
        this.$nextTick(() => {
            this._editor = suneditor.create(this.$refs.editor, {
                plugins: plugins,
                height: "auto",
                katex: katex,
                stickyToolbar: false,
                buttonList: defaultButtonList,
                lang: zh_cn,
                // shallow merge user define options
                ...this.editorOptions
            });
            this._setContents(this.value);
            this._editor.readOnly(this.readonly);
            this._setDisable(this.disable);

            this._editor.onChange = this._onEditorChange;
        });
    },
    beforeDestroy() {
        if (this._editor) {
            this._editor.destroy();
        }
    },
    methods: {
        _setDisable(disabled) {
            if (this._editor){
                disabled ? this._editor.disable() : this._editor.enable();
            }
        },
        _setContents(content) {
            if (this._editor) {
                if (content !== this._editor.getContents()) {
                    this._editor.setContents(content);
                }
            } else {
                throw Error("editor is not initialed");
            }
        },
        _onEditorChange(content) {
            this.$emit("input", content);
        },

        getEditorInstance() {
            return this._editor;
        },
    }
};
</script>
