// A tilemap node. The grid is uploaded once and rendered natively with per-frame view culling; the
// node's position is the bottom-left of the map. Edit cells with setTile.

import { Node2D } from "./Node2D"
import type { Texture2D } from "./Texture2D"

export type TilemapOptions = {
  texture: Texture2D
  /** Map grid size (in tiles). */
  cols: number
  rows: number
  /** On-screen cell size in world units — a single number (square) or [w, h]. */
  tile: number | [number, number]
  /** Atlas grid: how the texture is sliced into tiles, [atlasCols, atlasRows]. */
  atlas: [number, number]
  /** Row-major tile indices into the atlas (-1 = empty), length cols*rows. Row 0 is the top row. */
  data: number[] | Int32Array
}

export class Tilemap extends Node2D {
  readonly cols: number
  readonly rows: number

  constructor(options: TilemapOptions) {
    const data = options.data instanceof Int32Array ? options.data : Int32Array.from(options.data)
    const tileW = typeof options.tile === "number" ? options.tile : options.tile[0]
    const tileH = typeof options.tile === "number" ? options.tile : options.tile[1]
    const [ atlasCols, atlasRows ] = options.atlas
    const id = _creator2d.createTilemap(
      options.texture.id, options.cols, options.rows, tileW, tileH, atlasCols, atlasRows, data,
    )
    super(id) // wrap the native tilemap entity
    this.cols = options.cols
    this.rows = options.rows
  }

  setTile(x: number, y: number, index: number): this {
    _creator2d.setTile(this.id, x, y, index)
    return this
  }
}
