<template>
  <TilemapLayerC :tilemap="tileMap" :tileset="zoneEditorStore.tiles" :layerIndex="0" :cull-padding-x="10" :cull-padding-y="10" />
  <Controls :layer="layer" />
  <Toolbar :layer="layer" @eraser="eraser" @pencil="pencil" />
  <Tiles v-if="zoneEditorStore.tool === 'pencil' || zoneEditorStore.tool === 'eraser'" />
  <Walls v-if="zoneEditorStore.tool === 'pencil' || zoneEditorStore.tool === 'eraser'" />
  <ZoneSettings v-if="zoneEditorStore.zoneSettingsOpen" />
</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, onBeforeUnmount, ref, type Ref, watch } from 'vue'
import Controls from '@/components/utilities/Controls.vue'
import { useSocketStore } from '@/stores/socket'
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'
import Walls from '@/components/utilities/zoneEditor/Walls.vue'
import { generateTilemap } from '@/services/zone'

// Phavuer logic
let scene = useScene()
const socket = useSocketStore()
const zoneEditorStore = useZoneEditorStore()

let tileMap = generateTilemap(scene, 10, 10);
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)

onBeforeMount(() => {
  socket.connection.emit('gm:zone_editor:zone:request', { zoneId: socket.character.zoneId })
})

const tiles = Array.from({ length: 10 }, () => Array.from({ length: 10 }, () => 0))
zoneEditorStore.setTiles(tiles)
zoneEditorStore.tiles.forEach((row, y) => row.forEach((tile, x) => layer.putTileAt(tile, x, y)))

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

socket.connection.on('gm:zone_editor:zone:load', (data) => {
  tileMap = generateTilemap(scene, data.zone.width, data.zone.height);
  zoneEditorStore.setZoneSettings(data.zone)
  zoneEditorStore.setTiles(data.zone.tiles)
})

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

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

onBeforeUnmount(() => {
  zoneEditorStore.reset();
})
</script>
