<template>
  <div class="marquee">
    <div class="marquee__Wrapper">
      <div v-for="i in 2" :key="i" class="marquee__Text" :style="style">
        <div v-for="n in numberOf" :key="n" class="marquee__InnerText">
          <slot/>
        </div>
      </div>
    </div>
  </div>
</template>
<script>
export default {
  props: {
    reverse: {
      default: false
    },
    duration: {
      default: 10000
    },
  },
  
  data(){
    return{
      style: {},
      numberOf: 1,
      preventUpdated: true,
      resizeTimeout: undefined,
    }
  },

  updated() {
    if(!this.preventUpdated){
      this.getImagesAndCalculate()
    }
  },

  mounted(){
    this.getImagesAndCalculate()
    window.addEventListener('resize', this.recalculate)
  },

  destroyed(){
    window.removeEventListener('resize', this.recalculate)
  },

  methods: {
    calculate(){
      let width = this.$el.querySelector('.marquee__InnerText').clientWidth || 1;
      let fullWidth = document.documentElement.clientWidth;
      this.numberOf = Math.ceil(fullWidth/width) || 1;

      this.style = {
        animationPlayState: 'running',
        animationDuration: `${this.duration*this.numberOf}ms`,
        animationDirection: this.reverse ? 'reverse' : 'normal'
      }

      this.preventUpdated = true;
      setTimeout(() => {
        this.preventUpdated = false;
      }, 10);
    },

    recalculate(){
      if(this.resizeTimeout) clearTimeout(this.resizeTimeout)
      this.resizeTimeout = setTimeout(() => {
        this.calculate()
      }, 300);
    },

    getImagesAndCalculate(){
      this.$nextTick(async () => {
        let images = this.$el.querySelectorAll('img');
        if(images && images.length > 0){
          await new Promise(resolve => {
            let imagesLoaded = 0;
            for(let img of [...images]){
              img.addEventListener('load', () => {
                imagesLoaded++;
                if(imagesLoaded === images.length) resolve()
              })
            }
          })
        }
        this.calculate();
      })
    },
  },
}
</script>

<style lang="scss">
.marquee{
  overflow: hidden;
}

.marquee__Wrapper{
  display: inline-flex;
  white-space: nowrap;
}

.marquee__Text,
.marquee__InnerText{
  display: flex;
  align-items: flex-start;
}

.marquee__Text{
  will-change: transform;
  animation: marquee infinite linear;
  animation-play-state: paused;
}

@keyframes marquee{
  from{
    transform: translate3d(0, 0, 0);
  }
  to{
    transform: translate3d(-100%, 0, 0);
  }
}
</style>