<template>
  <Image v-if="gameStore.isTextureLoaded(props.placedMapObject.mapObject.id)" 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
  selectedPlacedMapObject: PlacedMapObject | null
  movingPlacedMapObject: PlacedMapObject | null
}>()

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

const imageProps = computed(() => ({
  alpha: props.movingPlacedMapObject?.id === props.placedMapObject.id ? 0.5 : 1,
  tint: props.selectedPlacedMapObject?.id === props.placedMapObject.id ? 0x00ff00 : 0xffffff,
  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>
