<template>
  <i class="svg-image" v-html="svgContent"></i>
</template>

<style lang="scss" scoped>
  .svg-image {
    display: flex;
    justify-content: center;
    align-items: center;
  }

  svg {
    flex: 1;
  }
</style>

<script lang="babel">
  let SVGStore = {}

  export default {
    name: 'HotpaySvgLoader',
    props: {
      src: String,
      textSlot: String
    },
    data: () => ({
      svgContent: null
    }),
    watch: {
      src () {
        this.svgContent = null
        this.loadSVG()
      }
    },
    methods: {
      setSVGContent () {
        let content = SVGStore[this.src].then(() => {
          if (this.textSlot) {
            content = content.replace('{{textSlot}}', this.textSlot)
          }

          this.svgContent = content
          this.$nextTick().then(() => {
            const dataset = [].filter.call(this.$el.attributes, attribute => /^data-/.test(attribute.name))

            dataset.forEach(data => {
              const childrenArray = Array.from(this.$el.querySelectorAll('*'))

              childrenArray.forEach(node => {
                node.setAttribute(data.name.toLowerCase(), '')
              })
            })
          })
        })
      },
      isSVG (mimetype) {
        return mimetype.indexOf('svg') >= 0
      },
      loadSVG () {
        if (!SVGStore.hasOwnProperty(this.src)) {
          SVGStore[this.src] = new Promise((resolve, reject) => {
            const request = new window.XMLHttpRequest()
            const self = this

            request.open('GET', this.src, true)
            request.onload = function () {
              const mimetype = this.getResponseHeader('content-type')

              if (this.status >= 200 && this.status < 400 && self.isSVG(mimetype)) {
                resolve(this.response)

                self.setSVGContent()
              } else {
                reject(new Error(`The file ${self.src} is not a valid SVG.`))
              }
            }
            request.send()
          })
        } else {
          this.setSVGContent()
        }
      }
    },
    mounted () {
      this.loadSVG()
    }
  }
</script>
