<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, tileToWorldXY } from '@/composables/mapComposable'
import { useGameStore } from '@/stores/gameStore'
import { Image, useScene } from 'phavuer'
import { computed, onMounted } from 'vue'
import config from '@/application/config'
import { useMapEditorComposable } from '@/composables/useMapEditorComposable'
import Tilemap = Phaser.Tilemaps.Tilemap
import TilemapLayer = Phaser.Tilemaps.TilemapLayer

const props = defineProps<{
  placedMapObject: PlacedMapObject,
  tileMap: Tilemap
  tileMapLayer: TilemapLayer
}>()

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

const imageProps = computed(() => ({
  alpha: mapEditor.movingPlacedObject.value?.id == props.placedMapObject.id ? 0.5 : 1,
  tint: mapEditor.selectedPlacedObject.value?.id == props.placedMapObject.id ? 0x00ff00 : 0xffffff,
  depth: calculateIsometricDepth(props.placedMapObject.positionX, props.placedMapObject.positionY, props.placedMapObject.mapObject.frameWidth, props.placedMapObject.mapObject.frameHeight),
  ...calculateObjectPlacement(props.placedMapObject),
  flipX: props.placedMapObject.isRotated,
  texture: props.placedMapObject.mapObject.id,
  originX: props.placedMapObject.mapObject.originX,
  originY: props.placedMapObject.mapObject.originY
}))

// ... existing code ...

function calculateObjectPlacement(mapObj: PlacedMapObject) : {x: number; y: number} {
  let position = tileToWorldXY(props.tileMapLayer, mapObj.positionX, mapObj.positionY)

  return {
    x: position.worldPositionX - mapObj.mapObject.frameWidth/2,
    y: position.worldPositionY - mapObj.mapObject.frameHeight + (config.tile_size.height * 1.5)
  }
}

// ... existing code ...

onMounted(async () => {
  await 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>
