<template>
  <Character v-for="item in mapStore.characters" :key="item.character.id" :tileMap :mapCharacter="item" />
</template>

<script setup lang="ts">
import type { MapCharacter, UUID } from '@/application/types'
import Character from '@/components/game/character/Character.vue'
import { useGameStore } from '@/stores/gameStore'
import { useMapStore } from '@/stores/mapStore'
import { onUnmounted } from 'vue'

const gameStore = useGameStore()
const mapStore = useMapStore()

const props = defineProps<{
  tileMap: Phaser.Tilemaps.Tilemap
}>()

gameStore.connection?.on('map:character:join', async (data: MapCharacter) => {
  mapStore.addCharacter(data)
})

gameStore.connection?.on('map:character:leave', (characterId: UUID) => {
  mapStore.removeCharacter(characterId)
})

gameStore.connection?.on('map:character:move', (data: { characterId: UUID; positionX: number; positionY: number; rotation: number; isMoving: boolean }) => {
  mapStore.updateCharacterPosition(data)
  // @TODO: Replace with universal class, composable or store
  if (data.characterId === gameStore.character?.id) {
    gameStore.character!.positionX = data.positionX
    gameStore.character!.positionY = data.positionY
    gameStore.character!.rotation = data.rotation
  }
})

gameStore.connection?.on('map:character:attack', (characterId: UUID) => {
  mapStore.updateCharacterProperty(characterId, 'isAttacking', true)
})

onUnmounted(() => {
  gameStore.connection?.off('map:character:join')
  gameStore.connection?.off('map:character:leave')
  gameStore.connection?.off('map:character:move')
})
</script>
