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'

const MAX_LIGHT = 100 // maximum level where light shines

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

  // stores the current grid of blocks, visible on the screen
  const _grid: Block[][] = new Array(height)
  // stores the limit to where light still shines,
  // for each column currently visible on the screen
  const _lightBarrier: number[] = [...new Array(width)].map(() => MAX_LIGHT)

  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 calcLightBarrier(columnOffset: number) {
    let previousBlock: Block = T.air

    for (let col = 0; col < width; col++) {
      for (let level = 0; level < MAX_LIGHT; level++) {
        let block = blockGen.generateBlock(level, col + columnOffset)
        block = blockExt.extendBlock(level, col, columnOffset, block, previousBlock)
        previousBlock = block

        if (!block.transparent) {
          _lightBarrier[col] = level
          break
        }
      }
    }
  }

  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.fillRow(level, column, row)
      blockExt.extendRow(level, column, row, previousRow)

      _grid[i] = row
    }
  }

  function sunLight(x: number, y: number) {
    calcLightBarrier(x)
    return _lightBarrier
  }

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

  return { grid, sunLight, change }
}
