export default {
  props: {
    tplData: {
      type: Object,
      default: () => ({})
    },
    tplPlaceholder: {
      type: Object,
      default: () => ({})
    },
    tplType: {
      type: String
    }
  },
  data() {
    return {
      currentScale: 3.5,
      cutLines: 15
    }
  },
  mounted() {
    if (this.tplType === 'card') {
      this.storeCardSize()
      this.generateInlineImg()
    }
  },
  methods: {
    storeCardSize() {
      this.setStoreAction('setCurrentCardSize', {
        width: this.width + this.cutLines * 2,
        height: this.height + this.cutLines * 2
      })
    },
    generateInlineImg() {
      const imgs = document.querySelectorAll('[data-base64="true"]')

      for (let y = 0; y < imgs.length; y++) {
        this.convertToBase64(imgs[y])
      }
    },
    convertToBase64(img) {
      const path = img.getAttribute('src')

      fetch(path)
        .then(res => res.blob())
        .then(blob => {
          const file = new File([blob], 'tmp.png', blob)
          const reader = new FileReader()

          reader.readAsDataURL(file)

          reader.onload = () => {
            img.setAttribute('src', reader.result)
          }
        })
    }
  },
  watch: {
    tplData() {
      setTimeout(() => {
        this.generateInlineImg()
      }, 500)
    }
  },
  computed: {
    /**
     * Get item value if the correspondant data exist, if not return the placeholder
     * @param {String} item
     * @return {String}
     */
    getItemValue() {
      return item => {
        if (this.tplData[item]) {
          return this.tplData[item]
        }

        return null
      }
    },
    scaledValue() {
      return (value, usePx = true) => {
        if (!usePx) {
          return value * this.currentScale
        }

        return `${value * this.currentScale}px`
      }
    }
  }
}
