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

<script setup lang="ts">
import { SocketEvent } from '@/application/enums'
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(SocketEvent.MAP_CHARACTER_JOIN, (data: MapCharacter) => {
  mapStore.addCharacter(data)
})

gameStore.connection?.on(SocketEvent.MAP_CHARACTER_LEAVE, (characterId: UUID) => {
  mapStore.removeCharacter(characterId)
})

gameStore.connection?.on(SocketEvent.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(SocketEvent.MAP_CHARACTER_ATTACK, (characterId: UUID) => {
  mapStore.updateCharacterProperty(characterId, 'isAttacking', true)
})

onUnmounted(() => {
  gameStore.connection?.off(SocketEvent.MAP_CHARACTER_ATTACK)
  gameStore.connection?.off(SocketEvent.MAP_CHARACTER_MOVE)
  gameStore.connection?.off(SocketEvent.MAP_CHARACTER_JOIN)
  gameStore.connection?.off(SocketEvent.MAP_CHARACTER_LEAVE)
})
</script>
