<template>
  <Image v-if="mapObject && gameStore.isTextureLoaded(props.placedMapObject.mapObject as string)" v-bind="imageProps" />
</template>

<script setup lang="ts">
import config from '@/application/config'
import type { MapObject, PlacedMapObject } from '@/application/types'
import { useMapEditorComposable } from '@/composables/useMapEditorComposable'
import { calculateIsometricDepth, loadMapObjectTextures, tileToWorldXY } from '@/services/mapService'
import { MapObjectStorage } from '@/storage/storages'
import { useGameStore } from '@/stores/gameStore'
import { Image, useScene } from 'phavuer'
import { computed, onMounted, ref, watch } from 'vue'

import Tilemap = Phaser.Tilemaps.Tilemap
import TilemapLayer = Phaser.Tilemaps.TilemapLayer

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

const scene = useScene()

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

const mapObject = ref<MapObject>()

async function initialize() {
  if (!props.placedMapObject.mapObject) return

  /**
   * Check if mapObject is an string or object, if its an object we assume its a mapObject and change it to a string
   * We do this because this component is shared with the map editor, which gets sent the mapObject as an object by the server
   */
  if (typeof props.placedMapObject.mapObject === 'object') {
    // @ts-ignore
    props.placedMapObject.mapObject = props.placedMapObject.mapObject.id
  }

  const mapObjectStorage = new MapObjectStorage()
  const _mapObject = await mapObjectStorage.get(props.placedMapObject.mapObject as string)
  if (!_mapObject) return

  mapObject.value = _mapObject

  await loadMapObjectTextures([_mapObject], scene)
}

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

  return {
    x: position.worldPositionX - mapObject.value!.frameWidth / 2,
    y: position.worldPositionY - mapObject.value!.frameHeight / 2 + config.tile_size.height
  }
}

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, mapObject.value!.frameWidth, mapObject.value!.frameHeight),
  ...calculateObjectPlacement(props.placedMapObject),
  flipX: props.placedMapObject.isRotated,
  texture: mapObject.value!.id,
  originX: mapObject.value!.originX,
  originY: mapObject.value!.originY
}))

watch(
  () => mapEditor.refreshMapObject.value,
  async () => {
    await initialize()
  }
)

onMounted(async () => {
  await initialize()
})
</script>
