<template>
  <v-app>
    <div class="editorContainer">
      <textarea
        ref="csEditor"
        :id="id"
        v-mode="inputVal"
        :placeholder="placeholder"
        cols="60"
        rows="40"
        autofocus>
      </textarea>
    </div>
  </v-app>
</template>

<script>
const SMARTPHONE_LANDSCAPE_WIDTH = 768;
export default {
  props: {
    id: {
      type: String,
      default: () => {
        return 'cs-editor';
      }
    },
    value: {
      type: String,
      default: () => {
        return '';
      }
    },
    placeholder: {
      type: String,
      default: () => {
        return '';
      }
    },
    suggesterTypeOfRelation: {
      type: String,
      default: () => {
        return 'mention_activity_stream';
      },
    },
    suggesterSpaceURL: {
      type: String,
      default: () => {
        return eXo.env.portal.spaceUrl;
      },
    },
  },
  data() {
    return {
      inputVal: this.value,
      csEditor: null,
    };
  },
  computed: {
    isMobile() {
      return this.$vuetify.breakpoint.name === 'xs' || this.$vuetify.breakpoint.name === 'sm';
    },
    editorReady() {
      return this.editor && this.editor.status === 'ready';
    },
  },
  watch: {
    inputVal: function (val) {
      this.$emit('input', val);
    },
    /*value: function (val) {
      if (!this.editor) {
        this.initCKEditor();
      }
      this.initCKEditorData(val || '');
    },*/
    csEditor: {
      deep: true,
      handler(val) {
        if ( typeof val === 'undefined') {
          //this.initCKEditor(false);
        }
      }
    }
  },
  mounted() {
    this.initCKEditor(true);
  },
  methods: {
    initCKEditor(reset) {
      this.csEditor = CKEDITOR.instances[this.id];
      if (this.csEditor && this.csEditor.destroy) {
        if (reset) {
          this.csEditor.destroy(true);
        } else {
          this.initCKEditorData(this.value);
          this.setEditorReady();
          return;
        }
      }
      CKEDITOR.dtd.$removeEmpty['i'] = false;
      let extraPlugins = 'simpleLink,selectImage,suggester,font,justify,widget';
      const removePlugins = 'image,confirmBeforeReload,maximize,resize';
      const windowWidth = $(window).width();
      const windowHeight = $(window).height();
      if (windowWidth > windowHeight && windowWidth < SMARTPHONE_LANDSCAPE_WIDTH) {
        // Disable suggester on smart-phone landscape
        extraPlugins = 'simpleLink';
      }
      CKEDITOR.plugins.addExternal('embedsemantic', '/commons-extension/eXoPlugins/embedsemantic/', 'plugin.js');
      CKEDITOR.basePath = '/commons-extension/ckeditor/';
      const self = this;
      $(this.$refs.csEditor).ckeditor({
        customConfig: '/commons-extension/ckeditorCustom/config.js',
        extraPlugins,
        removePlugins,
        allowedContent: true,
        enterMode: CKEDITOR.ENTER_P,
        shiftEnterMode: CKEDITOR.ENTER_BR,
        typeOfRelation: self.suggesterTypeOfRelation,
        spaceURL: self.suggesterSpaceURL,
        toolbarLocation: 'top',
        toolbar: [
          { name: 'format', items: ['Format'] },
          { name: 'basicstyles', items: [ 'Bold', 'Italic', 'Underline', 'Strike', '-', 'RemoveFormat'] },
          { name: 'paragraph', items: [ 'NumberedList', 'BulletedList', '-', 'Blockquote' ] },
          { name: 'fontsize', items: ['FontSize'] },
          { name: 'align', items: [ 'JustifyLeft', 'JustifyCenter', 'JustifyRight', 'JustifyBlock'] },
          { name: 'links', items: [ 'simpleLink', 'selectImage'] },
        ],
        height: 250,
        autoGrow_maxHeight: 500,
        autoGrow_minHeight: 250,
        format_tags: 'p;h1;h2;h3',
        dialog_noConfirmCancel: true,
        bodyClass: 'csEditorContent',
        contentsCss: ['body {font-size: 18px;font-family:arial;}'],
        on: {
          instanceReady: function () {
            self.editor = CKEDITOR.instances[self.id];
            $(self.editor.document.$).find('.atwho_inserted').each(function () {
              $(this).on('click', '.remove', function () {
                $(this).closest('[data-atwho-at-query]').remove();
              });
            });
            self.setEditorReady();
            if (self.autofocus) {
              window.setTimeout(() => self.setFocus(), 50);
            }
          },
          change: function (event) {
            const newData = event.editor.getData();
            self.inputVal = newData;
          },
          destroy: function () {
            self.inputVal = '';
            self.editor = null;
          }
        }
      });
    },
    initCKEditorData(message) {
      if (message) {
        const tempDiv = $('<div class=\'temp\'/>').html(message);
        tempDiv.find('a[href*="/profile"]').each(function () {
          $(this).replaceWith(function () {
            return $('<span/>',{
              class: 'atwho_inserted',
              html: `<span class="exo-mention">${$(this).text()}
                       <a data-cke-survive href="#" class="remove">
                         <i data-cke-survive class="uiIconClose uiIconLightGray"></i></a></span>`
            }).attr('data-atwho-at-query',`@${$(this).attr('href').substring($(this).attr('href').lastIndexOf('/')+1)}`)
              .attr('data-atwho-at-value',$(this).attr('href').substring($(this).attr('href').lastIndexOf('/')+1))
              .attr('contenteditable','false');
          });
        });
        message = tempDiv.html();
      }
      try {
        if (this.editor) {
          this.editor.setData(message);
        }
      } catch (e) {
        // When CKEditor not initialized or is detroying
      }
    },
    destroyCKEditor: function () {
      if (this.editor) {
        this.editor.destroy(true);
      }
    },
    setEditorReady: function() {
      this.$set(this.editor, 'status', 'ready');
    },
    setFocus: function() {
      if (this.editorReady) {
        window.setTimeout(() => {
          this.$nextTick().then(() => this.editor.focus());
        }, 200);
      }
    },
    getMessage: function() {
      const newData = this.editor && this.editor.getData();
      return newData ? newData : '';
    },
  }

};
</script>
