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

<script setup lang="ts">
import config from '@/config'
import { useScene } from 'phavuer'
import { useZoneEditorStore } from '@/stores/zoneEditorStore'
import { onMounted, onUnmounted } 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 zoneTilemap = createTilemap()
const tiles = 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 tilemap = new Phaser.Tilemaps.Tilemap(scene, zoneData)
  emit('tilemap:create', tilemap)
  return tilemap
}

/**
 * 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 zoneTilemap.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(zoneTilemap.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 = zoneTilemap.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(tiles, pointer.worldX, pointer.worldY)
  if (!tile) return

  // Place tile
  placeTile(zoneTilemap, tiles, 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(tiles, pointer.worldX, pointer.worldY)
  if (!tile) return

  // Place tile
  placeTile(zoneTilemap, tiles, 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(zoneTilemap, tiles, createTileArray(zoneTilemap.width, zoneTilemap.height, zoneEditorStore.selectedTile.id))

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

// 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(tiles, pointer.worldX, pointer.worldY)
  if (!tile) return

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

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

  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)

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