<template>
  <div class='SimpleIcon' ref="SimpleIconRef" />
</template>

<script>
const cacheIcon = {

}

export default {
  name: 'SimpleIcon',
  props: {
    /**
     * [pattern, replacement]
     */
    replaces: {
      type: Array,
      default: () => []
    },
    url: {
      type: String,
      default: null
    }
  },
  async created() {
    if (!cacheIcon[this.url]) {
      await fetch(this.url).then(async data => {
        cacheIcon[this.url] = await new Response(data.body).text();
      })
    };

    this._icon_replace_data = cacheIcon[this.url].replaceAll(...this.replaces);

    this.insertHTML();
  },
  mounted() {
    this.insertHTML();
  },
  methods: {
    insertHTML() {
      const el = this.$refs.SimpleIconRef;
      if (!el) return;

      el.innerHTML = this._icon_replace_data;

      if (el.firstElementChild) {
        const svg = el.firstElementChild;
        el.replaceWith(el.firstElementChild)

        this.$nextTick(() => {
          for (let key in el.dataset) {
            svg.dataset[key] = "";
          }

          el.classList.forEach(className => svg.classList.add(className))
        });
      }
    }
  }
}
</script>

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