import type { NoiseFunction2D } from 'simplex-noise'
import {blockTypes as T, level as L, probability as P, type Block} from './def'

function trees(r: number, i: number, row: Block[], previousRow: Block[]) {
  const max = row.length - 1
  const h = i - 1
  const j = i + 1

  if (row[i] === T.treeTopMiddle) {
    if (i) {
      if (row[h] === T.treeTopRight) row[h] = T.treeTopLeftMixed
      else row[h] = T.treeTopLeft
    }
    if (i < max) row[j] = T.treeTopRight

  } else if (previousRow[i] === T.treeTopMiddle) {
    row[i] = T.treeCrownMiddle
    if (i) {
      if (row[h] === T.treeCrownRight) row[h] = T.treeCrownLeftMixed
      else row[h] = T.treeCrownLeft
    }
    if (i < max) row[j] = T.treeCrownRight
  } else if (previousRow[i] === T.treeCrownMiddle) {
    row[i] = T.treeTrunkMiddle
    if (i) {
      if (row[h] === T.treeTrunkRight) row[h] = T.treeTrunkLeftMixed
      else row[h] = T.treeTrunkLeft
    }
    if (i < max) row[j] = T.treeTrunkRight
  } else if (previousRow[i] === T.treeTrunkMiddle) {
    row[i] = T.treeRootMiddle
    if (i) {
      if (row[h] === T.treeRootRight) row[h] = T.treeRootLeftMixed
      else row[h] = T.treeRootLeft
    }
    if (i < max) row[j] = T.treeRootRight
  }
}

function ground(r: number, i: number, row: Block[], previousRow: Block[]) {
  const rootParts = [T.treeRootLeft, T.treeRootMiddle, T.treeRootRight]
  const prevBlock = previousRow[i]

  if (prevBlock === T.air) {
    if (r < P.soilHole) row[i] = T.air
    else if (row[i] === T.soil) row[i] = T.grass
  } else if (rootParts.indexOf(prevBlock) >= 0) {
    if (row[i] === T.soil) row[i] = T.grass
  }
}

function rock(r: number, i: number, row: Block[], previousRow: Block[]) {
  if (previousRow[i] === T.soil && r < P.fray) row[i] = T.soil
}

function underground(r: number, i: number, row: Block[], previousRow: Block[]) {
  if (previousRow[i] === T.stone && r < P.fray) row[i] = T.stone
}

export default function createBlockExtender(rand: NoiseFunction2D) {
  function extendBlocks(level: number, column: number, row: Block[], previousRow: Block[]) {
    for (let i = 0; i < row.length; i++) {
      const r = rand(level, column + i)

      if (level < L.ground) trees(r, i, row, previousRow)
      else if (level < L.rock) ground(r, i, row, previousRow)
      else if (level < L.underground) rock(r, i, row, previousRow)
      else underground(r, i, row, previousRow)
    }
  }

  return extendBlocks
}
