<template>
<img ref="sprite" v-show="loaded"
    class="sprite pixelated"
    :src="frame_paths[0]" 
    :width="props.width">
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue';

const props = defineProps<{
  path: string,
  frames: string,
  top?: string,
  right?: string,
  left?: string,
  bottom?: string,
  width: string,
  fps?: string
}>();

const sprite = ref(null);
const loaded = ref(false);

let frame_paths = [];
for(let i = 1; i <= parseInt(props.frames); i++){
    frame_paths.push(props.path + "frame" + i + ".png");
}

let current = 0;
const fps = props.fps ? parseInt(props.fps) : 4;

function preloadImages(imageArray) {
  return Promise.all(
    imageArray.map(src => {
      return new Promise((resolve, reject) => {
        const img = new Image();
        img.src = src;
        img.onload = resolve;
        img.onerror = reject;
      });
    })
  );
}

onMounted(() => {
    sprite.value.style.top = props.top;
    sprite.value.style.left = props.left;
    sprite.value.style.bottom = props.bottom;
    sprite.value.style.right = props.right;
    
    loaded.value = true;
    
    preloadImages(frame_paths).then(() => {
        setInterval(() => {
            current = (current + 1) % frame_paths.length;
            sprite.value.src = frame_paths[current];
        }, 1000 / fps);
    });
    
});
</script>

<style lang="scss" scoped>
.sprite {
    position: absolute;
    z-index: -10;
}
</style>