<template>
  <Controls v-if="isInitialized" :layer="tileLayer" :depth="0" />
</template>

<script setup lang="ts">
import config from '@/application/config'
import type { UUID } from '@/application/types'
import { unduplicateArray } from '@/application/utilities'
import Controls from '@/components/utilities/Controls.vue'
import { FlattenMapArray, loadMapTilesIntoScene, setLayerTiles } from '@/composables/mapComposable'
import { MapStorage } from '@/storage/storages'
import { useMapStore } from '@/stores/mapStore'
import { useScene } from 'phavuer'
import { onBeforeUnmount, onMounted, ref } from 'vue'

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

const scene = useScene()
const mapStore = useMapStore()
const mapStorage = new MapStorage()

let tileMap: Phaser.Tilemaps.Tilemap
let tileLayer: Phaser.Tilemaps.TilemapLayer
let isInitialized = ref(false)

function createTileMap(mapData: any) {
  const mapConfig = new Phaser.Tilemaps.MapData({
    width: mapData?.width,
    height: mapData?.height,
    tileWidth: config.tile_size.width,
    tileHeight: config.tile_size.height,
    orientation: Phaser.Tilemaps.Orientation.ISOMETRIC,
    format: Phaser.Tilemaps.Formats.ARRAY_2D
  })

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

  return newTileMap
}

function createTileLayer(mapData: any) {
  const tilesArray = unduplicateArray(FlattenMapArray(mapData?.tiles ?? []))

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

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

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

  return layer
}

async function initialize() {
  try {
    await loadMapTilesIntoScene(mapStore.mapId as UUID, scene)
    const mapData = await mapStorage.get(mapStore.mapId)
    tileMap = createTileMap(mapData)
    tileLayer = createTileLayer(mapData)
    setLayerTiles(tileMap, tileLayer, mapData?.tiles)
    isInitialized.value = true
  } catch (error) {
    console.error('Failed to initialize map:', error)
  }
}

onMounted(() => {
  initialize()
})

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