<template>
  <p
    class="spellcheck"
    v-if="corrections">
    <span class="inline-title">Rechtschreibung:</span> <span v-html="highlightedText"/>
  </p>
</template>

<script>
  export default {
    props: ['corrections', 'text'],

    computed: {
      highlightedText() {
        if (!this.corrections) {
          return '';
        }
        let parts = [];
        let index = 0;
        [...this.corrections] // no side effects, as sort changes the source array
          .sort((e1, e2) => (e1.offset + e1.sentenceOffset) - (e2.offset + e2.sentenceOffset))
          .forEach(current => {
            let realOffset = current.offset + current.sentenceOffset;
            parts.push({
              correct: true,
              text: this.text.substring(index, realOffset)
            }, {
              correct: false,
              text: this.text.substring(realOffset, realOffset + current.length)
            });
            index = realOffset + current.length;
          });
        parts.push({
          correct: true,
          text: this.text.substring(index, this.text.length + 1)
        });
        return parts
          .filter(part => part.text.length)
          .reduce((previous, part) => {
            if (part.correct) {
              return `${previous}${part.text}`;
            } else {
              return `${previous}<span data-cy="spellcheck-correction" class="spellcheck__correction">${part.text}</span>`;
            }
          }, '');
      }
    }
  };
</script>

<style lang="scss">
  @import "@/styles/_mixins.scss";

  .spellcheck {
    @include regular-text;

    &__correction {
      background: yellow;
    }
  }
</style>
