<template>
  <div style="display: flex; align-items: center; justify-content: center;" @click="next">
    <img style="width: 100%;" :src="currentImage.url" :alt="currentImage.name"/>
  </div>
</template>

<script>
export default {
  name: "RawImageCarousel",
  props: ['images', 'nameLabel', 'urlLabel'],
  watch: {
    images: {
      deep: true,
      handler: function (newVal, oldVal) {
        if(this.internalImages !== newVal)
          this.index = 0;
        this.getCurrentImage();
      },
    }
  },
  created() {
    this.getCurrentImage();
  },
  data() {
    return {
      index: 0,
      internalImages: null,
      currentImage: {
        name: '',
        url: '',
      },
    };
  },
  methods: {
    next() {
      this.index++;
      if(this.index >= this.images.length)
        this.index = 0;
      this.getCurrentImage();
    },
    getCurrentImage() {
      let img = this.index >= this.images.length ? null : this.images[this.index];
      if(img)
      {
        if(typeof(img) === 'object')
        {
          this.currentImage.url = this.getValue(img, this.urlLabel);
          this.currentImage.name = this.getValue(img, this.nameLabel);
        }
        else
          this.currentImage.url = img;
      }
      else
      {
        this.currentImage.url = '';
      }
    },
    getValue(obj, field) {
      switch (typeof field)
      {
        case 'string':
          return obj[field] || '';
          case 'function':
            return field(obj) || '';
            default:
              return obj || '';
      }
    }
  }
}
</script>

<style scoped>

</style>
