<template>
  <picture data-vue-component-name="AppImage">
    <source
      v-if="webp"
      :srcset="cachedImages[webp]"
      type="image/webp"
    >

    <img
      v-if="png"
      :src="cachedImages[png]"
      :alt="alt"
    >
  </picture>
</template>

<script setup>
import { reactive, watch } from 'vue';
import { request, excludeKeys, forEach } from '@xsys2/functions';

const props = defineProps({
  webp: {
    type: String,
    default: null,
  },
  png: {
    type: String,
    default: null,
  },
  alt: {
    type: String,
    default: null,
  },
});

const cachedImages = reactive({});

function isImageExistInCache(url) {
  return Object.prototype.hasOwnProperty.call(props, url);
}

async function requestBlob(url) {
  return request({ method: 'GET', url, responseType: 'blob' });
}

function convertBlobToImage(blob) {
  return (window.URL || window.webkitURL).createObjectURL(blob);
}

function saveImageToCache(url, image) {
  cachedImages[url] = image;
}

watch(
  props,
  (value) => {
    forEach(excludeKeys(value, 'alt'), (_propName, url) => {
      if (!isImageExistInCache(url)) {
        requestBlob(url)
          .then(convertBlobToImage)
          .then(image => saveImageToCache(url, image));
      }
    });
  },
  {
    immediate: true,
  },
);
</script>
