<template>
  <div class="editor">
    <textarea name="editor" :id="textareaElementId" :disabled="disabled"></textarea>
  </div>
</template>

<script>
import { uniqueId } from 'lodash'
export default {
  name: 'VEditor',
  props: {
    value: { type: String },
    disabled: { type: Boolean, default: null }
  },
  data() {
    return {
      textareaElementId: uniqueId('editor_'),
      ckEditor: null
    }
  },
  watch: {
    value(val) {
      if (this.ckEditor && this.ckEditor.getData() !== val) {
        this.ckEditor.setData(val)
      }
    },
    disabled(val) {
      if (this.ckEditor && this.ckEditor.instanceReady) {
        this.ckEditor.setReadOnly(val)
      }
    }
  },
  methods: {
    createEditor() {
      const config = {
        height: 400,
        uiColor: '#eeeeee',
        filebrowserImageUploadUrl: '/api/ck/form/ckeditor-upload',
        fileTools_requestHeaders: { tenant: 'kelley' },
        // resize_enabled: typeof this.props.resizable === 'boolean' ? this.props.resizable : true,
        toolbar: [
          // { name: 'document', items: ['Source', '-', 'Save', 'NewPage', 'Preview'] },
          { name: 'styles', items: ['Styles', 'Format', 'Font', 'FontSize'] },
          { name: 'colors', items: ['TextColor', 'BGColor'] },
          { name: 'tools', items: ['Maximize', 'ShowBlocks'] },
          // { name: 'clipboard', items: ['Cut', 'Copy', 'Paste', 'PasteText', 'PasteFromWord', '-', 'Undo', 'Redo'] },
          { name: 'editing', items: ['Find', 'Replace'] },
          // { name: 'forms', items: ['Form', 'Checkbox', 'Radio', 'TextField', 'Textarea', 'Select', 'Button', 'ImageButton', 'HiddenField'] },
          '/',
          {
            name: 'basicstyles',
            items: [
              'Bold',
              'Italic',
              'Underline',
              'Strike',
              'Subscript',
              'Superscript',
              '-',
              'RemoveFormat'
            ]
          },
          {
            name: 'paragraph',
            items: [
              'NumberedList',
              'BulletedList',
              '-',
              'Outdent',
              'Indent',
              '-',
              'Blockquote',
              'CreateDiv',
              '-',
              'JustifyLeft',
              'JustifyCenter',
              'JustifyRight',
              'JustifyBlock',
              '-',
              'BidiLtr',
              'BidiRtl'
            ]
          },
          { name: 'links', items: ['Link', 'Unlink', 'Anchor'] },
          { name: 'insert', items: ['Image', 'Table', 'HorizontalRule'] }
        ]
      }

      if (this.disabled !== null) {
        config.readOnly = this.disabled
      }

      const editor = (this.ckEditor = CKEDITOR.replace(
        this.textareaElementId,
        config
      ))
      editor.on('instanceReady', () => {
        const data = this.value
        editor.fire('lockSnapshot')

        editor.setData(data, {
          callback: () => {
            this.bindEvent()

            const newData = editor.getData()
            // Locking the snapshot prevents the 'change' event.
            // Trigger it manually to update the bound data.
            if (data !== newData) {
              this.$once('input', () => {
                this.$emit('ready', editor)
              })

              this.$emit('input', newData)
            } else {
              this.$emit('ready', editor)
            }

            editor.fire('unlockSnapshot')
          }
        })
      })
    },
    bindEvent() {
      const editor = this.ckEditor
      editor.on('change', evt => {
        const data = editor.getData()
        if (this.value !== data) {
          this.$emit('input', data, evt, editor)
        }
      })

      editor.on('focus', evt => {
        this.$emit('focus', evt, editor)
      })

      editor.on('blur', evt => {
        this.$emit('blur', evt, editor)
      })
    }
  },
  mounted() {
    this.createEditor()
  },
  beforeDestroy() {
    this.ckEditor && this.ckEditor.destroy()
    this.ckEditor = null
  }
}
</script>

<style lang="scss" scoped>
* {
  margin: 0;
  padding: 0;
}
</style>
