import config from '@/config'
import Tilemap = Phaser.Tilemaps.Tilemap
import TilemapLayer = Phaser.Tilemaps.TilemapLayer
import Tileset = Phaser.Tilemaps.Tileset

export function getTile(x: number, y: number, layer: Phaser.Tilemaps.TilemapLayer): Phaser.Tilemaps.Tile | undefined {
  const tile: Phaser.Tilemaps.Tile = layer.getTileAtWorldXY(x, y)
  if (!tile) return undefined
  return tile
}

export function tileToWorldXY(layer: Phaser.Tilemaps.TilemapLayer, pos_x: number, pos_y: number) {
  const worldPoint = layer.tileToWorldXY(pos_x, pos_y)
  const position_x = worldPoint.x + config.tile_size.y
  const position_y = worldPoint.y

  return { position_x, position_y }
}

export function tileToWorldX(layer: Phaser.Tilemaps.TilemapLayer, pos_x: number, pos_y: number): number {
  const worldPoint = layer.tileToWorldXY(pos_x, pos_y)
  return worldPoint.x + config.tile_size.x / 2
}

export function tileToWorldY(layer: Phaser.Tilemaps.TilemapLayer, pos_x: number, pos_y: number): number {
  const worldPoint = layer.tileToWorldXY(pos_x, pos_y)
  return worldPoint.y + config.tile_size.y * 1.5
}

export function placeTile(zone: Tilemap, layer: TilemapLayer, x: number, y: number, tileName: string) {
  const tileImg = zone.getTileset(tileName) as Tileset
  if (!tileImg) return
  layer.putTileAt(tileImg.firstgid, x, y)
}

export function setAllTiles(zone: Tilemap, layer: TilemapLayer, tiles: string[][]) {
  tiles.forEach((row, y) => {
    row.forEach((tile, x) => {
      placeTile(zone, layer, x, y, tile)
    })
  })
}
