<template>
  <Image v-if="gameStore.getLoadedAsset(props.zoneObject.object.id)" v-bind="imageProps" />
</template>

<script setup lang="ts">
import { computed } from 'vue'
import { Image, useScene } from 'phavuer'
import { calculateIsometricDepth, tileToWorldX, tileToWorldY } from '@/composables/zoneComposable'
import { loadTexture } from '@/composables/gameComposable'
import type { AssetDataT, ZoneObject } from '@/application/types'
import { useGameStore } from '@/stores/gameStore'

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

const gameStore = useGameStore()
const scene = useScene()

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)
}))

loadTexture(scene, {
  key: props.zoneObject.object.id,
  data: '/assets/objects/' + props.zoneObject.object.id + '.png',
  group: 'objects',
  updatedAt: props.zoneObject.object.updatedAt,
  frameWidth: props.zoneObject.object.frameWidth,
  frameHeight: props.zoneObject.object.frameHeight
} as AssetDataT).catch((error) => {
  console.error('Error loading texture:', error)
})
</script>
