<template>
  <TilemapLayerC :tilemap="tileMap" :tileset="zoneStore.tiles" ref="tilemapLayer" :layerIndex="0" :cull-padding-x="10" :cull-padding-y="10" />
  <Controls :layer="layer" />
  <Toolbar :layer="layer" @erase="erase" @tile="tile" />
  <Tiles />
  <ZoneSettings />
</template>

<script setup lang="ts">
import config from '@/config'
import Tileset = Phaser.Tilemaps.Tileset
import TilemapLayer = Phaser.Tilemaps.TilemapLayer
import { Container, TilemapLayer as TilemapLayerC, useScene } from 'phavuer'
import { onBeforeMount, ref, type Ref, watch } from 'vue'
import Controls from '@/components/utilities/Controls.vue'
import { useSocketStore } from '@/stores/socket'
import { useZoneStore } from '@/stores/zone'
import Toolbar from '@/components/utilities/zoneEditor/Toolbar.vue'
import Tiles from '@/components/utilities/zoneEditor/Tiles.vue'
import { useZoneEditorStore } from '@/stores/zoneEditor'
import ZoneSettings from '@/components/utilities/zoneEditor/ZoneSettings.vue'

// Phavuer logic
let scene = useScene()
let tilemapLayer = ref()
let zoneData = new Phaser.Tilemaps.MapData({
  width: 10, // @TODO : get this from the server
  height: 10, // @TODO : get this from the server
  tileWidth: config.tile_size.x,
  tileHeight: config.tile_size.y,
  orientation: Phaser.Tilemaps.Orientation.ISOMETRIC,
  format: Phaser.Tilemaps.Formats.ARRAY_2D
})
let tileMap = new Phaser.Tilemaps.Tilemap(scene, zoneData)
let tileset: Tileset = tileMap.addTilesetImage('default', 'tiles') as Tileset
let layer: TilemapLayer = tileMap.createBlankLayer('layer', tileset, 0, config.tile_size.y) as TilemapLayer

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

// Multiplayer / server logics
const zoneStore = useZoneStore()
const zoneEditorStore = useZoneEditorStore()
const socket = useSocketStore()

zoneStore.setTiles([
  [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
  [0, 1, 1, 1, 1, 1, 1, 1, 1, 0],
  [0, 1, 1, 1, 1, 1, 1, 1, 1, 0],
  [0, 1, 1, 1, 1, 1, 1, 1, 1, 0],
  [0, 1, 1, 1, 1, 1, 1, 1, 1, 0],
  [0, 1, 1, 1, 1, 1, 1, 1, 1, 0],
  [0, 1, 1, 1, 1, 1, 1, 1, 1, 0],
  [0, 1, 1, 1, 1, 1, 1, 1, 1, 0],
  [0, 1, 1, 1, 1, 1, 1, 1, 1, 0],
  [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
])
zoneStore.tiles.forEach((row, y) => row.forEach((tile, x) => layer.putTileAt(tile, x, y)))

// Watch for changes in the zoneStore and update the layer
watch(
  () => zoneStore.tiles,
  () => {
    // @TODO : change to tiles for when loading other maps
    zoneStore.tiles.forEach((row, y) => row.forEach((tile, x) => layer.putTileAt(tile, x, y)))
  },
  { deep: true }
)

function erase(tile: Phaser.Tilemaps.Tile) {
  layer.putTileAt(0, tile.x, tile.y)
}

function tile(tile: Phaser.Tilemaps.Tile) {
  if (zoneEditorStore.selectedTile === null) return
  layer.putTileAt(zoneEditorStore.selectedTile, tile.x, tile.y)
}
</script>
