import config from '@/application/config'
import type { HttpResponse, TextureData, Tile as TileT, UUID } from '@/application/types'
import { unduplicateArray } from '@/application/utilities'
import { loadTexture } from '@/composables/gameComposable'
import { MapStorage, TileStorage } from '@/storage/storages'

import Tilemap = Phaser.Tilemaps.Tilemap
import TilemapLayer = Phaser.Tilemaps.TilemapLayer
import Tileset = Phaser.Tilemaps.Tileset
import Tile = Phaser.Tilemaps.Tile

export function getTile(layer: TilemapLayer | Tilemap, positionX: number, positionY: number): Tile | null {
  return layer.getTileAtWorldXY(positionX, positionY)
}

export function tileToWorldXY(layer: TilemapLayer | Tilemap, positionX: number, positionY: number) {
  const worldPoint = layer.tileToWorldXY(positionX, positionY)
  if (!worldPoint) return { worldPositionX: 0, worldPositionY: 0 }

  const worldPositionX = worldPoint.x + config.tile_size.height
  const worldPositionY = worldPoint.y

  return { worldPositionX, worldPositionY }
}

export function tileToWorldX(layer: TilemapLayer | Tilemap, positionX: number, positionY: number): number {
  const worldPoint = layer.tileToWorldXY(positionX, positionY)
  if (!worldPoint) return 0

  return worldPoint.x + config.tile_size.width / 2
}

export function tileToWorldY(layer: TilemapLayer | Tilemap, positionX: number, positionY: number): number {
  const worldPoint = layer.tileToWorldXY(positionX, positionY)
  if (!worldPoint) return 0

  return worldPoint.y + config.tile_size.height * 1.5
}

/**
 * Can also be used to replace tiles
 * @param map
 * @param layer
 * @param positionX
 * @param positionY
 * @param tileName
 */
export function placeTile(map: Tilemap, layer: TilemapLayer, positionX: number, positionY: number, tileName: string) {
  let tileImg = map.getTileset(tileName) as Tileset
  if (!tileImg) {
    tileImg = map.getTileset('blank_tile') as Tileset
  }
  layer.putTileAt(tileImg.firstgid, positionX, positionY)
}

export function setLayerTiles(map: Tilemap, layer: TilemapLayer, tiles: string[][]) {
  if (!tiles) return

  tiles.forEach((row: string[], y: number) => {
    row.forEach((tile: string, x: number) => {
      placeTile(map, layer, x, y, tile)
    })
  })
}

export function createTileArray(width: number, height: number, tile: string = 'blank_tile') {
  return Array.from({ length: height }, () => Array.from({ length: width }, () => tile))
}

export const calculateIsometricDepth = (positionX: number, positionY: number, width: number = 0, height: number = 0, isCharacter: boolean = false) => {
  const baseDepth = positionX + positionY
  if (isCharacter) {
    return baseDepth // @TODO: Fix collision, this is a hack
  }
  return baseDepth + (width + height) / (2 * config.tile_size.width)
}

async function getTiles(tiles: TileT[], scene: Phaser.Scene) {
  // Load each tile into the scene
  for (const tile of tiles) {
    if (!tile) continue
    const textureData = {
      key: tile.id,
      data: '/textures/tiles/' + tile.id + '.png',
      group: 'tiles',
      updatedAt: tile.updatedAt
    } as TextureData
    await loadTexture(scene, textureData)
  }
}

export async function loadMapTilesIntoScene(map_id: UUID, scene: Phaser.Scene) {
  const tileStorage = new TileStorage()
  const mapStorage = new MapStorage()
  const map = await mapStorage.get(map_id)
  if (!map) return

  const tileArray = unduplicateArray(map.tiles)
  const tiles = await tileStorage.getByIds(tileArray)

  await getTiles(tiles, scene)
}

export async function loadTilesIntoScene(tileIds: string[], scene: Phaser.Scene) {
  const tileStorage = new TileStorage()
  const tiles = await tileStorage.getByIds(tileIds)

  await getTiles(tiles, scene)
}

export async function loadAllTilesIntoScene(scene: Phaser.Scene) {
  const tileStorage = new TileStorage()
  const tiles = await tileStorage.getAll()

  await getTiles(tiles, scene)
}
