<template>
  <Tiles :key="zoneStore.zone?.id ?? 0" @tilemap:create="tileMap = $event" />
  <Objects v-if="tileMap" :tilemap="tileMap as Phaser.Tilemaps.Tilemap" />
  <Characters v-if="tileMap" :tilemap="tileMap as Phaser.Tilemaps.Tilemap" />
</template>

<script setup lang="ts">
import { useScene } from 'phavuer'
import { useGameStore } from '@/stores/game'
import { useZoneStore } from '@/stores/zone'
import { onBeforeUnmount, ref } from 'vue'
import type { Character as CharacterT, Zone as ZoneT, ExtendedCharacter as ExtendedCharacterT } from '@/types'
import Tiles from '@/components/zone/Tiles.vue'
import Objects from '@/components/zone/Objects.vue'
import Characters from '@/components/zone/Characters.vue'
import { loadAssets } from '@/composables/zoneComposable'

const gameStore = useGameStore()
const zoneStore = useZoneStore()
const scene = useScene()

const tileMap = ref(null as Phaser.Tilemaps.Tilemap | null)

type zoneLoadData = {
  zone: ZoneT
  characters: CharacterT[]
}

gameStore.connection!.emit('zone:character:join', { zoneId: gameStore.character!.zoneId }, async (response: zoneLoadData) => {
  // Fetch assets for new zone
  await gameStore.fetchZoneAssets(response.zone.id)
  await loadAssets(scene)

  // Set zone and characters
  zoneStore.setZone(response.zone)
  zoneStore.setCharacters(response.characters)
})

// Event listeners
gameStore.connection!.on('zone:teleport', async (data: zoneLoadData) => {
  if (zoneStore.zone?.id === data.zone.id) return

  // Fetch assets for new zone
  await gameStore.fetchZoneAssets(data.zone.id)
  // wait 1.5 sec
  await loadAssets(scene)

  /**
   * @TODO : Update character via global event server-side, remove this and listen for it somewhere not here
   */
  gameStore.setCharacter({
    ...gameStore.character!,
    zoneId: data.zone.id
  })

  zoneStore.setZone(data.zone)
  zoneStore.setCharacters(data.characters)
})

gameStore.connection!.on('zone:character:join', async (data: ExtendedCharacterT) => {
  zoneStore.addCharacter(data)
})

gameStore.connection!.on('zone:character:leave', (character_id: number) => {
  zoneStore.removeCharacter(character_id)
})

gameStore.connection!.on('character:move', (data: ExtendedCharacterT) => {
  zoneStore.updateCharacter(data)
})

onBeforeUnmount(() => {
  zoneStore.reset()
  gameStore.connection!.off('zone:teleport')
  gameStore.connection!.off('zone:character:join')
  gameStore.connection!.off('zone:character:leave')
  gameStore.connection!.off('character:move')
})
</script>
