
var getEle = fp.curry(function(ele) {
  return (document.querySelectorAll(ele).length === 1) ? document.querySelector(ele) : [...document.querySelectorAll(ele)]; 
});


function hexColor() {
  var values = "01233456789ABCDEF";
  var result = [];
  for(var i = 0; i < 6; i++) {
    result.push(values[Math.floor(Math.random() * 16)]);
  }
  return '#'+result.join('');
}

var css = fp.curry(function(cssObj, ele) { 
  for(var key in cssObj) {
    ele.style[key] = cssObj[key];
  }
  return ele; 
}); 



//--------------------------------


var count_neighbours = function(r, c, grid) {
  var count = 0;
  if (r > 0) {
    count += grid[r-1][c];
  }
  if (r < grid.length-1) {
    count += grid[r+1][c];
  }
  if (c > 0) {
    count += grid[r][c-1];
  }
  if (c < grid.length[0]-1) {
    count += grid[r][c+1];
  }
  return count;
};


var update_grid = function(grid) {
  var count;
  var nrows = grid.length;
  var ncols = grid[0].length;
  for (var r=0; r<nrows; r++) {
    for (var c=0; c<ncols; c++) {
      count = count_neighbours(r, c, grid);
      if (grid[r][c] == 1 && count > 2) {
        grid[r][c] = 0;
      }
      if (grid[r][c] == 0 && count <= 2) {
        grid[r][c] = 1;
      }
    }
  }
  return grid;
};


var render_grid = fp.curry(function(ctx, grid) {
  var height = ctx.canvas.height;
  var width= ctx.canvas.width;
  var nrows = grid.length;
  var ncols = grid[0].length;

  ctx.clearRect(0, 0, width, height);
  for (var r=0; r<nrows; r++) {
    for (var c=0; c<ncols; c++) {
      ctx.fillStyle = (grid[r][c] == 0) ? '#fff':'#000';
      ctx.fillRect(c*width/ncols+0.5, r*height/nrows+0.5, width/ncols-0.5, height/nrows-0.5);
    }
  }

  return grid;
});


var app = function(canvas_id, timestep, grid_init) {
  var canvas = document.getElementById(canvas_id);
  var ctx = canvas.getContext('2d');
  var render = render_grid(ctx);
  var state = grid_init;
  setInterval(function() {

    //state = render_grid(ctx, update_grid(state));
    state = fp.pipe(render, update_grid)(state);
  }, timestep);
};


var grid0 = [
 [1,0,0,0,1,1,1,1,0,0,0,0],
 [1,0,0,0,1,1,1,1,0,0,0,0],
 [1,0,0,0,1,1,1,1,0,0,0,0],
 [1,0,0,0,1,1,1,1,0,0,0,0],
 [1,0,0,0,1,1,1,1,0,0,0,0],
 [1,0,0,0,1,1,1,1,0,0,0,0],
 [1,0,0,0,1,1,1,1,0,0,0,0],
 [1,0,0,0,1,1,1,1,0,1,1,0],
 [1,0,0,0,1,1,1,1,0,0,0,0],
 [1,0,0,0,1,1,1,1,0,0,0,0],
 [1,0,0,0,1,1,1,1,0,0,0,0],
 [1,0,0,0,1,1,1,1,0,0,0,0]
];

var random_grid = function(nrows, ncols) {
  var grid = []
  for (var r=0; r<nrows; r++) {
    grid[r] = [];
    for (var c=0; c<ncols; c++) {
      grid[r][c] = (Math.random() > 0.8) ? 1:0;
    }
  }
  console.log(grid);
  return grid;
}

//app("board", 500, grid0);
app("board", 500, random_grid(200, 200));
