<template>
  <img
    :src="srcUrl"
    :width="_width"
    :height="_height"
    :alt="_alt"
  />
</template>

<script lang="ts">
import Vue from 'vue';

const isDev = (process.env.NODE_ENV !== 'production')
let observer!: any;

export default Vue.extend({
  name: 'Img',
  props: {
    src: {
      type: String
    },
    height: {
      type: Number
    },
    width: {
      type: Number
    },
    alt: {
      type: String
    },
    base64: {
      type: String
    },
    nolazy: {
      type: String
    },
    lazydistance: {
      type: Number
    }
  },
  data() {
    return {
      intersected : false,
      srcData : ''
    }
  },
  computed: {
      _src():any {
        return this.src
      },
      _alt():any {
        return this.alt
      },
      _width():any {
        return this.width
      },
      _height():any {
        return this.height
      },
      srcUrl():any {
        if(this.nolazy === undefined || this.nolazy === null) {
          if(!isDev) {
            return this.srcData
          } else {
            return this.src
          }
        }
        else
          return this.src
      }
  },
  mounted() {
    let lazydistance = (this.lazydistance === undefined || this.lazydistance === null) ? "0px" : this.lazydistance + "px"
    const options = { rootMargin: lazydistance };

    if(!isDev) {

        observer = new IntersectionObserver(entries => {
            const entry = entries[0];

            if (entry.isIntersecting) {
                this.intersected = true;
                observer.disconnect();

                if(this.src) {
                    this.loadImage().then((base:any) => {
                        this.srcData = base
                    })
                }
            }
        }, options);

        observer.observe(this.$el);
    }

    if (this.base64 === undefined || this.base64 === null) {
    } else {
        if( this.base64.startsWith("data:image") ) {
        this.srcData = this.base64
        } else {
        this.srcData = 'data:image/jpeg;base64,' + this.base64
        }
    }
  },
  destroyed() {
    if(observer)
        observer.disconnect();
  },
  methods: {
    loadImage(){
        return new Promise((resolve) => {
            if(typeof this.src === 'string') {
            fetch(this.src)
                .then(response => response.blob())
                .then(blob => {
                const reader = new FileReader()
                reader.onloadend = () => {
                    return resolve(reader.result)
                }
                reader.readAsDataURL(blob)
                })
            } else {
            return ""
            }
        })
    },
  }
})
</script>

<style scoped>
img {
  -webkit-transition: all 1s ease-in-out;
  -moz-transition: all 1s ease-in-out;
  -o-transition: all 1s ease-in-out;
  transition: all 1s ease-in-out;
}
</style>
