<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" :key="object.object.id" :x="object.position_x" :y="object.position_y" :texture="object.object.id" :originY="Number(object.object.origin_x)" :originX="Number(object.object.origin_y)" />
  </Container>

  <Toolbar :layer="tiles" @eraser="eraser" @pencil="pencil" @paint="paint" @save="save" />
  <Tiles v-if="((zoneEditorStore.tool === 'pencil' || zoneEditorStore.tool === 'eraser') && zoneEditorStore.drawMode === 'tile') || zoneEditorStore.tool === 'paint'" />
  <Objects v-if="(zoneEditorStore.tool === 'pencil' || zoneEditorStore.tool === 'eraser') && zoneEditorStore.drawMode === 'object'" />
  <ZoneSettings v-if="zoneEditorStore.isSettingsModalShown" />
  <ZoneList v-if="zoneEditorStore.isZoneListModalShown" />
</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 { 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 { placeTile, setAllTiles, tileToWorldXY } from '@/services/zone'
import { useAssetStore } from '@/stores/assets'
import Objects from '@/components/utilities/zoneEditor/Objects.vue'
import type { ZoneObject } from '@/types'
import { storeToRefs } from 'pinia'
import ZoneList from '@/components/utilities/zoneEditor/ZoneList.vue'
import Tileset = Phaser.Tilemaps.Tileset
import TilemapLayer = Phaser.Tilemaps.TilemapLayer

const scene = useScene()
const socket = useSocketStore()
const zoneEditorStore = useZoneEditorStore()
const assetStore = useAssetStore()

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

/**
 * This array is used to store the tileset images
 */
const tilesetImages: Tileset[] = []

/**
 * Create a new tilemap which will be used to draw the zone
 */
const zoneTilemap = new Phaser.Tilemaps.Tilemap(scene, zoneData)

/**
 * This array is used to store the tileset key for each tile in the zone
 */
let zoneTiles = [] as string[][];

/**
 * This array is used to store the objects in the zone
 */
const zoneObjects = ref<ZoneObject[]>([])

/**
 * 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: zoneEditorStore.zone?.width ?? 0 }, () => Array.from({ length: zoneEditorStore.zone?.height ?? 0 }, () => 'blank_tile'))

const { objectList } = storeToRefs(zoneEditorStore)

/**
 * Watch for object updates and update the zoneObjects
 */
watch(objectList, (newObjects) => {
  zoneObjects.value = zoneObjects.value.map((object) => {
    const newObject = newObjects.find((newObject) => newObject.id === object.object.id)
    if (!newObject) return object
    return { ...object, object: newObject }
  })
})

function eraser(tile: Phaser.Tilemaps.Tile) {
  if (zoneEditorStore.drawMode === 'tile') {
    placeTile(zoneTilemap, tiles, tile.x, tile.y, 'blank_tile')
    zoneTiles[tile.y][tile.x] = 'blank_tile'
  }

  if (zoneEditorStore.drawMode === 'object') {
    zoneObjects.value = zoneObjects.value.filter((object) => {
      const worldXY = tileToWorldXY(tiles, tile.x, tile.y)
      return object.position_x !== worldXY.position_x || object.position_y !== worldXY.position_y
    })
  }
}

function pencil(tile: Phaser.Tilemaps.Tile) {
  if (zoneEditorStore.drawMode === 'tile') {
    if (!zoneEditorStore.selectedTile) return
    placeTile(zoneTilemap, tiles, tile.x, tile.y, zoneEditorStore.selectedTile)
    zoneTiles[tile.y][tile.x] = zoneEditorStore.selectedTile
  }

  if (zoneEditorStore.drawMode === 'object') {
    if (zoneEditorStore.zone === null) return
    if (zoneEditorStore.selectedObject === null) return

    zoneObjects.value.push({
      id: Math.random(),
      zoneId: zoneEditorStore.zone.id,
      zone: zoneEditorStore.zone,
      objectId: zoneEditorStore.selectedObject.id,
      object: zoneEditorStore.selectedObject,
      position_x: tileToWorldXY(tiles, tile.x, tile.y).position_x,
      position_y: tileToWorldXY(tiles, tile.x, tile.y).position_y
    })

    // remove duplicates based on object, pos x and y
    zoneObjects.value = zoneObjects.value.filter((object, index, self) => index === self.findIndex((t) => t.objectId === object.objectId && t.position_x === object.position_x && t.position_y === object.position_y))
  }
}

function paint(tile: Phaser.Tilemaps.Tile) {
  if (!zoneEditorStore.selectedTile) return
  exampleTilesArray.forEach((row, y) => row.forEach((tile, x) => placeTile(zoneTilemap, tiles, x, y, zoneEditorStore.selectedTile)))
  zoneTiles.forEach((row, y) => row.forEach((tile, x) => zoneTiles[y][x] = zoneEditorStore.selectedTile))
}

function save() {
  if (!zoneEditorStore.zone) return

  console.log(zoneTiles);

  socket.connection.emit('gm:zone_editor:zone:update', {
    zoneId: zoneEditorStore.zone.id,
    name: zoneEditorStore.zone.name,
    width: zoneTilemap.width,
    height: zoneTilemap.height,
    tiles: zoneTiles,
    objects: zoneObjects.value
  })
}

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

  if (zoneEditorStore.zone && zoneEditorStore.zone.tiles) {
    setAllTiles(zoneTilemap, tiles, zoneEditorStore.zone.tiles)
    zoneTiles = zoneEditorStore.zone.tiles
  }
  zoneObjects.value = zoneEditorStore.zone?.zoneObjects ?? []
})

onBeforeUnmount(() => {
  tiles.destroy()
  zoneTilemap.removeAllLayers()
  zoneTilemap.destroy()
  zoneEditorStore.reset()
})

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