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

<script setup lang="ts">
import config from '@/config'
import { useScene } from 'phavuer'
import { useZoneStore } from '@/stores/zoneStore'
import { onBeforeUnmount } from 'vue'
import { FlattenZoneArray, setLayerTiles } from '@/composables/zoneComposable'
import Controls from '@/components/utilities/Controls.vue'
import { unduplicateArray } from '@/utilities'

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

const scene = useScene()
const zoneStore = useZoneStore()
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: zoneStore.zone?.width,
    height: zoneStore.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 = unduplicateArray(FlattenZoneArray(zoneStore.zone?.tiles ?? []))

  const tilesetImages = Array.from(tilesArray).map((tile: any, index: number) => {
    return tileMap.addTilesetImage(tile, tile, 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
}

setLayerTiles(tileMap, tileLayer, zoneStore.zone?.tiles)

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