<template>
  <div class="tip-tap">
    <editor-content class="tip-tap__editor-wrapper" :editor="editor" />

    <toggle :bordered="false" :checked="isList" label="Als Liste formatieren" @input="toggleList" />
  </div>
</template>

<script lang="ts">
import Vue, { PropType } from 'vue';
import { Editor, EditorContent } from '@tiptap/vue-2';
import Document from '@tiptap/extension-document';
import Paragraph from '@tiptap/extension-paragraph';
import Text from '@tiptap/extension-text';
import BulletList from '@tiptap/extension-bullet-list';
import ListItem from '@tiptap/extension-list-item';
import Toggle from '@/components/ui/Toggle.vue';

interface Data {
  editor: Editor | undefined;
}
interface Value {
  text: string;
}

export default Vue.extend({
  props: {
    value: {
      type: Object as PropType<Value>,
      validator(value: Value) {
        return Object.prototype.hasOwnProperty.call(value, 'text');
      },
    },
  },

  components: {
    Toggle,
    EditorContent,
  },

  data(): Data {
    return {
      editor: undefined,
    };
  },

  computed: {
    isList(): boolean {
      return this.editor?.isActive('bulletList') || false;
    },
    text(): string {
      return this.value.text;
    },
  },

  watch: {
    value({ text }: Value) {
      const editor = this.editor as Editor; // editor is always initialized on mount, cast it
      const isSame = editor.getHTML() === text;

      if (isSame) {
        return;
      }

      editor.commands.setContent(text, false);
    },
  },

  mounted() {
    this.editor = new Editor({
      editorProps: {
        attributes: {
          class: 'tip-tap__editor',
        },
      },
      content: this.text,
      extensions: [Document, Paragraph, Text, BulletList, ListItem],
      onUpdate: () => {
        const text = (this.editor as Editor).getHTML();
        this.$emit('input', text);
        this.$emit('change-text', text);
      },
    });
  },

  beforeDestroy() {
    this.editor?.destroy();
  },

  methods: {
    toggleList() {
      const editor = this.editor as Editor;
      editor.chain().selectAll().toggleBulletList().run();
    },
  },
});
</script>

<style scoped lang="scss">
@import '~styles/helpers';

.tip-tap {
  &__editor-wrapper {
    margin-bottom: $medium-spacing;
  }

  :deep(.tip-tap__editor) {
    @include inputstyle;
    flex-direction: column;
    min-height: 150px;
  }

  :deep(ul) {
    padding-left: $medium-spacing;
    list-style: initial;
  }

  :deep(li) {
    @include inputfont;
  }

  :deep(div) {
    @include inputfont;
  }

  :deep(p) {
    @include inputfont;
  }
}
</style>
