<template>
  <Controls :layer="tileLayer" :depth="0" />
</template>

<script setup lang="ts">
import config from '@/config'
import { useScene } from 'phavuer'
import { useZoneEditorStore } from '@/stores/zoneEditorStore'
import { onMounted, onUnmounted, watch } from 'vue'
import { createTileArray, getTile, placeTile, setLayerTiles } from '@/composables/zoneComposable'
import Controls from '@/components/utilities/Controls.vue'
import { useGameStore } from '@/stores/gameStore'
import type { AssetDataT } from '@/types'

const emit = defineEmits(['tileMap:create'])

const scene = useScene()
const gameStore = useGameStore()
const zoneEditorStore = useZoneEditorStore()
const tileMap = createTileMap()
const tileLayer = createTileLayer()

/**
 * A Tilemap is a container for Tilemap data.
 * This isn't a display object, rather, it holds data about the map and allows you to add tilesets and tilemap layers to it.
 * A map can have one or more tilemap layers, which are the display objects that actually render the tiles.
 */
function createTileMap() {
  const zoneData = new Phaser.Tilemaps.MapData({
    width: zoneEditorStore.zone?.width,
    height: zoneEditorStore.zone?.height,
    tileWidth: config.tile_size.x,
    tileHeight: config.tile_size.y,
    orientation: Phaser.Tilemaps.Orientation.ISOMETRIC,
    format: Phaser.Tilemaps.Formats.ARRAY_2D
  })

  const newTileMap = new Phaser.Tilemaps.Tilemap(scene, zoneData)
  emit('tileMap:create', newTileMap)

  return newTileMap
}

/**
 * A Tileset is a combination of a single image containing the tiles and a container for data about each tile.
 */
function createTileLayer() {
  const tilesArray = gameStore.getLoadedAssetsByGroup('tiles')

  const tilesetImages = Array.from(tilesArray).map((tile: AssetDataT, index: number) => {
    return tileMap.addTilesetImage(tile.key, tile.key, config.tile_size.x, config.tile_size.y, 1, 2, index + 1, { x: 0, y: -config.tile_size.y })
  }) as any

  // Add blank tile
  tilesetImages.push(tileMap.addTilesetImage('blank_tile', 'blank_tile', config.tile_size.x, config.tile_size.y, 1, 2, 0, { x: 0, y: -config.tile_size.y }))
  const layer = tileMap.createBlankLayer('tiles', tilesetImages, 0, config.tile_size.y) as Phaser.Tilemaps.TilemapLayer

  layer.setDepth(0)
  layer.setCullPadding(2, 2)

  return layer
}

function pencil(pointer: Phaser.Input.Pointer) {
  // Check if zone is set
  if (!zoneEditorStore.zone) return

  // Check if tool is pencil
  if (zoneEditorStore.tool !== 'pencil') return

  // Check if draw mode is tile
  if (zoneEditorStore.drawMode !== 'tile') return

  // Check if there is a selected tile
  if (!zoneEditorStore.selectedTile) return

  // Check if left mouse button is pressed
  if (!pointer.isDown) return

  // Check if shift is not pressed, this means we are moving the camera
  if (pointer.event.shiftKey) return

  // Check if there is a tile
  const tile = getTile(tileLayer, pointer.worldX, pointer.worldY)
  if (!tile) return

  // Place tile
  placeTile(tileMap, tileLayer, tile.x, tile.y, zoneEditorStore.selectedTile)

  // Adjust zoneEditorStore.zone.tiles
  zoneEditorStore.zone.tiles[tile.y][tile.x] = zoneEditorStore.selectedTile
}

function eraser(pointer: Phaser.Input.Pointer) {
  // Check if zone is set
  if (!zoneEditorStore.zone) return

  // Check if tool is pencil
  if (zoneEditorStore.tool !== 'eraser') return

  // Check if draw mode is tile
  if (zoneEditorStore.eraserMode !== 'tile') return

  // Check if left mouse button is pressed
  if (!pointer.isDown) return

  // Check if shift is not pressed, this means we are moving the camera
  if (pointer.event.shiftKey) return

  // Check if alt is pressed
  if (pointer.event.altKey) return

  // Check if there is a tile
  const tile = getTile(tileLayer, pointer.worldX, pointer.worldY)
  if (!tile) return

  // Place tile
  placeTile(tileMap, tileLayer, tile.x, tile.y, 'blank_tile')

  // Adjust zoneEditorStore.zone.tiles
  zoneEditorStore.zone.tiles[tile.y][tile.x] = 'blank_tile'
}

function paint(pointer: Phaser.Input.Pointer) {
  // Check if zone is set
  if (!zoneEditorStore.zone) return

  // Check if tool is pencil
  if (zoneEditorStore.tool !== 'paint') return

  // Check if there is a selected tile
  if (!zoneEditorStore.selectedTile) return

  // Check if left mouse button is pressed
  if (!pointer.isDown) return

  // Check if shift is not pressed, this means we are moving the camera
  if (pointer.event.shiftKey) return

  // Check if alt is pressed
  if (pointer.event.altKey) return

  // Set new tileArray with selected tile
  setLayerTiles(tileMap, tileLayer, createTileArray(tileMap.width, tileMap.height, zoneEditorStore.selectedTile))

  // Adjust zoneEditorStore.zone.tiles
  zoneEditorStore.zone.tiles = createTileArray(tileMap.width, tileMap.height, zoneEditorStore.selectedTile)
}

// When alt is pressed, and the pointer is down, select the tile that the pointer is over
function tilePicker(pointer: Phaser.Input.Pointer) {
  // Check if zone is set
  if (!zoneEditorStore.zone) return

  // Check if tool is pencil
  if (zoneEditorStore.tool !== 'pencil') return

  // Check if draw mode is tile
  if (zoneEditorStore.drawMode !== 'tile') return

  // Check if left mouse button is pressed
  if (!pointer.isDown) return

  // Check if shift is not pressed, this means we are moving the camera
  if (pointer.event.shiftKey) return

  // Check if alt is pressed
  if (!pointer.event.altKey) return

  // Check if there is a tile
  const tile = getTile(tileLayer, pointer.worldX, pointer.worldY)
  if (!tile) return

  // Select the tile
  zoneEditorStore.setSelectedTile(zoneEditorStore.zone.tiles[tile.y][tile.x])
}

watch(
  () => zoneEditorStore.shouldClearTiles,
  (shouldClear) => {
    if (shouldClear && zoneEditorStore.zone) {
      const blankTiles = createTileArray(tileMap.width, tileMap.height, 'blank_tile')
      setLayerTiles(tileMap, tileLayer, blankTiles)
      zoneEditorStore.zone.tiles = blankTiles
      zoneEditorStore.resetClearTilesFlag()
    }
  }
)

onMounted(() => {
  if (!zoneEditorStore.zone?.tiles) {
    return
  }

  // First fill the entire map with blank tiles using current zone dimensions
  const blankTiles = createTileArray(zoneEditorStore.zone.width, zoneEditorStore.zone.height, 'blank_tile')

  // Then overlay the zone tiles, but only within the current zone dimensions
  const zoneTiles = zoneEditorStore.zone.tiles
  for (let y = 0; y < zoneEditorStore.zone.height; y++) {
    for (let x = 0; x < zoneEditorStore.zone.width; x++) {
      // Only copy if the source tiles array has this position
      if (zoneTiles[y] && zoneTiles[y][x] !== undefined) {
        blankTiles[y][x] = zoneTiles[y][x]
      }
    }
  }

  setLayerTiles(tileMap, tileLayer, blankTiles)

  scene.input.on(Phaser.Input.Events.POINTER_MOVE, pencil)
  scene.input.on(Phaser.Input.Events.POINTER_MOVE, eraser)
  scene.input.on(Phaser.Input.Events.POINTER_DOWN, paint)
  scene.input.on(Phaser.Input.Events.POINTER_DOWN, tilePicker)
})

onUnmounted(() => {
  scene.input.off(Phaser.Input.Events.POINTER_MOVE, pencil)
  scene.input.off(Phaser.Input.Events.POINTER_MOVE, eraser)
  scene.input.off(Phaser.Input.Events.POINTER_DOWN, paint)
  scene.input.off(Phaser.Input.Events.POINTER_DOWN, tilePicker)

  tileMap.destroyLayer('tiles')
  tileMap.removeAllLayers()
  tileMap.destroy()
})
</script>
