<template>
  <TilemapLayerC :tilemap="zoneTilemap" :tileset="exampleTilesArray" :layerIndex="0" :cull-padding-x="10" :cull-padding-y="10" />
  <Controls :layer="tiles" />

  <Container :depth="2">
    <Image
      v-for="object in zoneObjects"
      :depth="object.depth"
      :key="object.object.id"
      :x="tileToWorldX(zoneTilemap, object.position_x, object.position_y)"
      :y="tileToWorldY(zoneTilemap, object.position_x, object.position_y)"
      :texture="object.object.id"
      :originY="Number(object.object.origin_x)"
      :originX="Number(object.object.origin_y)"
    />
    <Character :layer="zoneTilemap" v-for="character in zoneStore.characters" :key="character.id" :character="character" />
  </Container>

  <Container :depth="3">
    <Image v-for="zoneEventTile in zoneEventTiles" :key="zoneEventTile.id" :x="tileToWorldX(zoneTilemap, zoneEventTile.position_x, zoneEventTile.position_y)" :y="tileToWorldY(zoneTilemap, zoneEventTile.position_x, zoneEventTile.position_y)" :texture="zoneEventTile.type" />
  </Container>
</template>

<script setup lang="ts">
import config from '@/config'
import { Container, Image, TilemapLayer as TilemapLayerC, useScene } from 'phavuer'
import { onBeforeMount, onBeforeUnmount, ref, toRaw, watch } from 'vue'
import Controls from '@/components/utilities/Controls.vue'
import { useGameStore } from '@/stores/game'
import { placeTile, setAllTiles, tileToWorldX, tileToWorldY } from '@/services/zone'
import { useAssetStore } from '@/stores/assets'
import type { Zone, ZoneEventTile, ZoneObject, Character as CharacterT } from '@/types'
import Tileset = Phaser.Tilemaps.Tileset
import TilemapLayer = Phaser.Tilemaps.TilemapLayer
import { useZoneStore } from '@/stores/zone'
import Character from '@/components/sprites/Character.vue'

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

const zoneData = new Phaser.Tilemaps.MapData({
  width: gameStore.character?.zone?.width ?? 10,
  height: gameStore.character?.zone?.height ?? 10,
  tileWidth: config.tile_size.x,
  tileHeight: config.tile_size.y,
  orientation: Phaser.Tilemaps.Orientation.ISOMETRIC,
  format: Phaser.Tilemaps.Formats.ARRAY_2D
})

/**
 * These variables are used to store the tileset images and the tilemap
 * The tilesetImages are used to store the tileset images
 * The zoneTilemap is used to store the tilemap
 * The zoneTiles are used to store the tile data
 * The zoneObjects are used to store the object data
 */
const tilesetImages: Tileset[] = []
const zoneTilemap = new Phaser.Tilemaps.Tilemap(scene, zoneData)
let zoneTiles = [] as string[][]
const zoneObjects = ref<ZoneObject[]>([])
const zoneEventTiles = ref<ZoneEventTile[]>([])

/**
 * Walk through object and add them to the zone as tilesetImages
 */
let tileCount = 1
toRaw(assetStore.assets).forEach((asset) => {
  if (asset.group !== 'tiles') return
  tilesetImages.push(zoneTilemap.addTilesetImage(asset.key, asset.key, config.tile_size.x, config.tile_size.y, 0, 0, tileCount++) as Tileset)
})
tilesetImages.push(zoneTilemap.addTilesetImage('blank_tile', 'blank_tile', config.tile_size.x, config.tile_size.y, 0, 0, 0) as Tileset)

const tiles = zoneTilemap.createBlankLayer('tiles', tilesetImages, 0, config.tile_size.y) as TilemapLayer
const exampleTilesArray = Array.from({ length: gameStore.character?.zone?.width ?? 0 }, () => Array.from({ length: gameStore.character?.zone?.height ?? 0 }, () => 'blank_tile'))

// Listen for player join events
gameStore.connection?.on('zone:character:join', (data: CharacterT) => {
  console.log('character:zone:join', data)
  zoneStore.addCharacter(data)
})

// Listen for user:disconnect
gameStore.connection?.on('zone:character:leave', (data: CharacterT) => {
  zoneStore.removeCharacter(data)
})

gameStore.connection?.on('character:moved', (data: CharacterT) => {
  console.log('character:moved', data)
  zoneStore.updateCharacter(data)
})

onBeforeMount(() => {
  exampleTilesArray.forEach((row, y) => row.forEach((tile, x) => placeTile(zoneTilemap, tiles, x, y, 'blank_tile')))
  zoneTiles = exampleTilesArray

  if (gameStore.character?.zone ?? gameStore.character?.zone?.tiles) {
    setAllTiles(zoneTilemap, tiles, gameStore.character?.zone?.tiles ?? [])
    zoneTiles = gameStore.character?.zone?.tiles ?? []

    // Determine the current zone dimensions
    const currentZoneWidth = gameStore.character?.zone?.width ?? 0
    const currentZoneHeight = gameStore.character?.zone?.height ?? 0

    // Ensure zoneTiles matches the current zone dimensions, filling new spaces with 'blank_tile'
    for (let y = 0; y < currentZoneHeight; y++) {
      zoneTiles[y] = zoneTiles[y] || [] // Ensure the row exists
      for (let x = 0; x < currentZoneWidth; x++) {
        zoneTiles[y][x] = zoneTiles[y][x] || 'blank_tile' // Fill missing tiles with 'blank_tile'
      }
    }

    // Update the tilemap with any new 'blank_tile' entries
    zoneTiles.forEach((row, y) => {
      row.forEach((tileId, x) => {
        placeTile(zoneTilemap, tiles, x, y, tileId)
      })
    })
  }

  zoneObjects.value = gameStore.character?.zone?.zoneObjects ?? []

  // Original
  type TResponse = {
    zone: Zone
    characters: CharacterT[]
  }

  gameStore.connection?.emit('character:zone:request', { zoneId: gameStore.character?.zoneId }, (response: TResponse) => {
    console.log(response)
    zoneStore.setZone(response.zone)
    zoneStore.setCharacters(response.characters)
    setAllTiles(zoneTilemap, tiles, response.zone.tiles)
    zoneObjects.value = response.zone.zoneObjects
  })
})

onBeforeUnmount(() => {
  zoneEventTiles.value = []
  zoneObjects.value = []
  tiles.destroy()
  zoneTilemap.removeAllLayers()
  zoneTilemap.destroy()
  zoneStore.reset()

  gameStore.connection?.emit('character:zone:leave')
  gameStore.connection?.off('character:zone:load')
  gameStore.connection?.off('zone:character:join')
  gameStore.connection?.off('user:disconnect')
  gameStore.connection?.off('character:moved')
})

// center camera
const centerY = (zoneTilemap.height * zoneTilemap.tileHeight) / 2
const centerX = (zoneTilemap.width * zoneTilemap.tileWidth) / 2
scene.cameras.main.centerOn(centerX, centerY)
</script>
