<template>
  <Image v-if="gameStore.isAssetLoaded(props.placedMapObject.mapObject)" v-bind="imageProps" />
</template>

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

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

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

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

loadTexture(scene, {
  key: props.placedMapObject.mapObject.id,
  data: '/textures/map_objects/' + props.placedMapObject.mapObject.id + '.png',
  group: 'map_objects',
  updatedAt: props.placedMapObject.mapObject.updatedAt,
  frameWidth: props.placedMapObject.mapObject.frameWidth,
  frameHeight: props.placedMapObject.mapObject.frameHeight
} as TextureData).catch((error) => {
  console.error('Error loading texture:', error)
})
</script>
