<template>
  <BackgroundImageLoader :image-url="imageUrls[activeIndex]"
                         @imageLoaded="handleImageLoaded"
  >
    <template slot="overlay">
      <slot name="overlay"></slot>
    </template>
  </BackgroundImageLoader>
</template>

<script>
import imageLoader from '~/mixins/imageLoader.js'
import BackgroundImageLoader from '@/components/BackgroundImageLoader'

export default {
  components: {
    BackgroundImageLoader,
  },

  mixins: [ imageLoader ],

  props: {
    imageUrls: {
      type: Array,
      required: true,
    },

    activeIndex: {
      type: Number,
      required: false,
      default () {
        return 0
      }
    }
  },

  data () {
    return {
      currentlyLoadingIndex: 1,
      errorUrls: [],
    }
  },

  mounted () {
    if (this.imageUrls.length > 1) {
      this.preloadImage()
    }
  },

  methods: {
    preloadImage () {
      this.loadImage(this.imageUrls[this.currentlyLoadingIndex])
        .then(img => {
          this.$emit('imageLoaded', img.src)
          console.log('imageloaded', img)
          this.currentlyLoadingIndex++
          if (this.currentlyLoadingIndex < this.imageUrls.length) {
            this.preloadImage()
          }
        })
        .catch(err => {
          // TODO handle error cases
          console.log('imageloaded ERROR', img.src)
        })
    },

    handleImageLoaded (img) {
      this.$emit('imageLoaded handler', img.src)
    }
  }
}
</script>

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