<script>

import Vue from 'vue'

export default {
  name: 'EdText',
  props: {
    tei: String,
    uuid: String,
    textid: String
  },
  data: () => ({
    template: null,
    html: null
  }),
  watch: {
    tei: function (newtei, oldtei) {
      // console.log('tei watcher', oldtei, newtei)
      // we need this watcher to update display as route is changing
      this.buildTemplate()
    }
  },
  beforeMount () {
    // console.log('EdText beforeMount')
    if (this.tei) {
      this.buildTemplate()
    }
  },
  methods: {
    buildTemplate () {
      // console.log('EdText buildTemplate: tei', this.tei)
      // to get Vue.compile working we have to use the full build of vuejs
      // https://vuejs.org/v2/guide/installation.html#Explanation-of-Different-Builds
      // in /build/webpack.config.base.js alias -> 'vue': 'vue/dist/vue.js',
      this.buildHtml()
      this.template = Vue.compile(this.html)
      this.$options.staticRenderFns = []
      this._staticTrees = []
      this.template.staticRenderFns.map(fn => (this.$options.staticRenderFns.push(fn)))
    },
    buildHtml () {
      this.html = `<div` +
      ` class="tei${this.uuid === this.textid ? ' active' : ''}"` +
      ` data-uuid="${this.uuid}"` +
      `>${this.tei}</div>`
      this.parseLinks()
      // console.log('EdText: builded html', this.html)
    },
    parseLinks () {
      let links = this.html.match(/<a[^<]+<\/a>/g)
      // console.log('links', links)
      if (links) {
        // let domparser = new DOMParser()
        // let domlink
        let linkparts, newlink, uuid
        let index = null
        for (var i = 0; i < links.length; i++) {
          // console.log(`link ${i}:`, links[i])
          linkparts = RegExp(/<a class="(.+)" href="(.+)" data-index="(.+)">(.+)<\/a>/g).exec(links[i], 'g')
          // console.log('linkparts', linkparts)
          if (!linkparts) {
            console.warn(`link ${i} malformed:`, links[i])
          } else {
            index = linkparts[3]
            uuid = linkparts[2].replace('#', '')
            newlink = `<a` +
              ` class="${linkparts[1]} active-link"` +
              ` data-index="${index}"` +
              ` data-uuid="${uuid}"` +
              ` href="/${index}/${uuid}"` +
              ` @click.prevent="onClickRef"` +
              ` @keyup.enter="onClickRef"` +
              ` @mouseover="onHoverLink"` +
              ` @mouseleave="onLeaveLink"` +
              `>${linkparts[4]}` +
              `<sup class="mdi mdi-message-text-outline" />` +
              `</a>`
            // console.log('newlink', newlink)
            this.html = this.html.replace(links[i], newlink)
          }
        }
        // console.log('this.html', this.html)
      }
    },
    onClickRef (e) {
      console.log('onClickRef(e)', e)
      this.$router.push({
        name: e.target.dataset.index,
        params: { id: e.target.dataset.uuid }
      })
    },
    onHoverLink (e) {
      console.log('EdText onHoverLink(e)', e)
      this.$emit('onHoverLink', {
        uuid: e.target.dataset.uuid,
        index: e.target.dataset.index,
        rect: e.target.getBoundingClientRect()
      })
    },
    onLeaveLink (e) {
      // console.log('EdText onLeaveLink(e)', e)
      this.$emit('onLeaveLink')
    }
  },
  render (h) {
    // console.log('EdText render()')
    if (!this.template) {
      return h('span', 'Loading ...')
    } else {
      return this.template.render.call(this)
    }
  }
}
</script>

<style lang="scss" scoped>
</style>
