<template>
  <Image v-if="isTextureLoaded" v-bind="imageProps" />
</template>

<script setup lang="ts">
import { ref, onMounted, computed } from 'vue'
import { Image, useScene } from 'phavuer'
import { calculateIsometricDepth, tileToWorldX, tileToWorldY } from '@/composables/zoneComposable'
import { useAssetManager } from '@/utilities/assetManager'
import type { ZoneObject } from '@/types'

const props = defineProps<{
  tilemap: Phaser.Tilemaps.Tilemap
  zoneObject: ZoneObject
}>()

const scene = useScene()
const assetManager = useAssetManager
const isTextureLoaded = ref(false)

const imageProps = computed(() => ({
  depth: calculateIsometricDepth(props.zoneObject.positionX, props.zoneObject.positionY, props.zoneObject.object.frameWidth, props.zoneObject.object.frameHeight),
  x: tileToWorldX(props.tilemap, props.zoneObject.positionX, props.zoneObject.positionY),
  y: tileToWorldY(props.tilemap, props.zoneObject.positionX, props.zoneObject.positionY),
  flipX: props.zoneObject.isRotated,
  texture: props.zoneObject.object.id,
  originY: Number(props.zoneObject.object.originX),
  originX: Number(props.zoneObject.object.originY)
}))

const loadTexture = async () => {
  const textureId = props.zoneObject.object.id

  // Check if the texture is already loaded in Phaser
  if (scene.textures.exists(textureId)) {
    isTextureLoaded.value = true
    return
  }

  let assetData = await assetManager.getAsset(textureId)

  if (!assetData) {
    await assetManager.downloadAsset(textureId, `/assets/objects/${textureId}.png`, 'objects', props.zoneObject.object.updatedAt)
    assetData = await assetManager.getAsset(textureId)
  }

  if (assetData) {
    return new Promise<void>((resolve) => {
      scene.textures.addBase64(textureId, assetData.data)
      scene.textures.once(`addtexture-${textureId}`, () => {
        isTextureLoaded.value = true
        resolve()
      })
    })
  }
}

onMounted(() => {
  loadTexture().catch((error) => {
    console.error('Error loading texture:', error)
  })
})
</script>
