import alea from 'alea'
import { createNoise2D, type NoiseFunction2D } from 'simplex-noise'
import createBlockGenerator from './blockGen'
import createBlockExtender from './blockExt'

import {blockTypes as T, level as L, type Block} from './def'

export default function createLevel(width: number, height: number, seed = 'very random seed') {
  const prng = alea(seed)
  const noise2D = createNoise2D(prng)
  const rand: NoiseFunction2D = (x, y) => 0.5 + 0.5 * noise2D(x, y)

  const _grid: Block[][] = new Array(height)
  const blockGen = createBlockGenerator(rand)
  const blockExt = createBlockExtender(rand)

  // Apply changes, coming from the player (tocktocktock-plopp!)
  function change (level: number, column: number, newBlock: Block) {
    // TODO
  }

  function generate(column: number, y: number) {
    for (let i = 0; i < height; i++) {
      const level = y+i
      const row: Block[] = Array(width)
      const previousRow = i ? _grid[i-1] : [] as Block[]

      blockGen(level, column, row, previousRow)
      blockExt(level, column, row, previousRow)

      _grid[i] = row
    }
  }

  function grid(x: number, y: number) {
    generate(x, y)
    return _grid
  }

  return { grid, change }
}
