<template>
  <img :src="srcImage" v-bind="$attrs" v-on="$listeners">
</template>

<script>
import {
  loadExternalScript,
  hasIntersectionObserverSupport
} from '../../../helpers';

function makeBlankImgSrc(width, height, color) {
  const src = encodeURIComponent(
    `<svg width="${width}" height="${height}" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 ${width} ${height}" preserveAspectRatio="none"> 
      <rect width="100%" height="100%" style="fill:${color};"></rect>
    </svg>`
  );
  return `data:image/svg+xml;charset=UTF-8,${src}`;
}

export default {
  name: 'EbImage',
  props: {
    src: String,
    height: {
      type: String,
      default: '300'
    },
    width: {
      type: String,
      default: '400'
    },
    color: {
      type: String,
      default: '#ccc'
    }
  },
  data: () => ({
    observer: null,
    intersected: false
  }),
  computed: {
    srcImage() {
      return this.intersected
        ? this.src
        : makeBlankImgSrc(this.width, this.height, this.color);
    }
  },
  mounted() {
    if (!hasIntersectionObserverSupport) {
      loadExternalScript(
        '//cdn.polyfill.io/v3/polyfill.min.js?features=IntersectionObserver'
      );
    }
    // It is supported, load the images
    this.observer = new IntersectionObserver(entries => {
      const image = entries[0];
      if (image.isIntersecting) {
        this.intersected = true;
        this.observer.disconnect();
      }
    });

    this.observer.observe(this.$el);
  },
  destroyed() {
    this.observer.disconnect();
  }
};
</script>