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

<script setup lang="ts">
import type { MapObject, PlacedMapObject } from '@/application/types'
import ImageGroup from '@/components/game/map/partials/ImageGroup.vue'
import { loadMapObjectTextures, tileToWorldXY } from '@/services/mapService'
import { MapObjectStorage } from '@/storage/storages'
import { useGameStore } from '@/stores/gameStore'
import { useScene } from 'phavuer'
import { computed, onMounted, ref } 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 mapObject = ref<MapObject>()

const groupProps = computed(() => ({
  ...calculateObjectPlacement(props.placedMapObject),
  mapObj: mapObject.value,
  obj: props.placedMapObject
}))

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.getById(props.placedMapObject.mapObject as string)
  if (!_mapObject) return

  console.log(_mapObject)

  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,
    y: position.worldPositionY
  }
}

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