+Perlin = require 'proc-noise'
+_ = require 'lodash'
+
 canvas = null
 
 createCanvas = (width,height) ->

  document.getElementById('game1').appendChild(canvas)
  return canvas

drawSquares = ->
  ctx = canvas.getContext('2d')
  ctx.fillStyle="#FF0000"
  x = 25
  y = 25
  w = 4
  h = 4
  ctx.fillRect(x,y,w,h)

generateData = (dw,dh,fn) ->
  rows = []
  for y in [0...dh]
    row = []
    for x in [0...dw]
      row.push fn(x,y)
    rows.push row
  return rows

drawStuff = (canvas,data,tileSize) ->
  ctx = canvas.getContext('2d')
  for row,i in data
    y = i * tileSize
    for c,j in row
      x = j * tileSize
      ctx.fillStyle = "rgb(#{c},#{c},#{c})"
      ctx.fillRect(x,y,tileSize,tileSize)


drawColorGrid = ->
  ctx = canvas.getContext('2d')
  for i in [0...6]
    for j in [0..6]
      ctx.fillStyle = 'rgb(' + Math.floor(255-42.5*i) + ',' + Math.floor(255-42.5*j) + ',0)'
      ctx.fillRect(j*25,i*25,25,25)

rando = (x,y) ->
  Math.floor(Math.random() * 100)+100

  Math.floor(Math.sqrt((dx*dx) + (dy*dy)) / 70 * 250)



mkNoiseFn = (params) ->
  perlin = new Perlin(params.seed)
  perlin.noiseDetail(params.lod, params.falloff)
  return (x,y) ->
    Math.floor(perlin.noise(x/params.scale,y/params.scale) * 255)

runNoiseExperiment = ->
  # Create a drawing surface
  canvas  = createCanvas(500,500)

  genParams =
    seed: 40
    lod: 6
    falloff: 0.6
    scale: 100

  # Create a drawing surface
  generateAndDrawChunk = (h,v) ->
    chw = 100
    buf = new Buffer2d(chw, chw)
    fn = mkNoiseFn(genParams)
    xoff= h * chw
    yoff= v * chw
    buf.populate(fn,xoff,yoff)
    drawBuffer(canvas,1,buf,xoff,yoff)

  # Make a list of chunks to create
  pairs = []
  for y in [0...5]
    for x in [0...5]
      pairs.push [x,y]
  pairs = _.shuffle(pairs) # shuffle them uot of order

  # In delayed fashion, walk through each chunk coord pair, generate and draw:
  walkThru = ->
    pair = pairs.pop()
    if pair
      generateAndDrawChunk pair[0],pair[1]
      setTimeout walkThru, 0
  setTimeout walkThru, 0


module.exports = runNoiseExperiment
