<template>
    <div v-show="visible"
         style="text-align: left !important;direction: ltr !important;"
         dir="ltr">
        <div :id="id"
             style="text-align: left !important;direction: ltr !important;"
             dir="ltr"></div>
        <button type="button"
                class="btn btn-secondary btn-sm"
                :class="cls">
            {{$t('copy')}}
        </button>
    </div>
</template>

<script>
import Clipboard from 'clipboard';
import { guid } from "libj-core";
import loc from './j-code-editor.resx';
import { i18n } from '../../localization/vue-i18n';
export default {
    i18n: i18n(loc),
    props: {
        value: {
            default: ''
        },
        canCopy: {
            default: true
        },
        visible: {
            default: false
        }
    },
    data() {
        return {
            id: guid.newId(),
            cls: guid.newId(),
            cm: null
        };
    },
    created() {
        this.$nextTick(() => {
            var id = this.id;
            this.cm = CodeMirror(document.getElementById(id), {
                value: this.value,
                lineNumbers: true,
                mode: "htmlmixed"
            });
            this.cm.on('change', this.onChange.bind(this));
            new Clipboard(`.${this.cls}`, {
                text: trigger => {
                    var res = this.getHtml();
                    this.$toast.show({
                        message: this.$t('textCopied'),
                        timeout: 1000
                    });
                    return res;
                }
            });
            setTimeout(() => {
                this.cm.refresh();
            }, 400);
        });
    },
    methods: {
        onChange(cm, change) {
            var html = this.getHtml();
            if (html !== this.value) {
                this.$emit('input', html);
            }
        },
        getHtml() {
            return this.cm.getDoc().getValue();
        },
        setHtml(html) {
            return this.cm.getDoc().setValue(html);
        }
    },
    watch: {
        value() {
            if (this.getHtml() !== this.value) {
                this.setHtml(this.value);
            }
        },
        visible() {
            if (this.visible) {
                setTimeout(() => {
                    this.cm.refresh();
                }, 400);
            }
        }
    }
}
</script>