/**
 * JavaLife - Conway's Life Simulation
 * @author Scott Hurring - scott at hurring dot com
 * @version alpha1
 * @license GPL
 * For most recent version, go to this url:
 * http://hurring.com/code/java/javalife/
 */

/**
 * This is the engine that drives the Life simulation.
 * 
 * It is responsible for computing each generation and
 * altering the field based on some rules of cell
 * life and death.
 */
public class LifeEngine
{
	JavaLife parent;
	private int generation;
	
	public LifeEngine(JavaLife parent) {
		this.parent = parent;
	}
	
	public void setGeneration(int i) {
		generation = i;
	}

	public int getGeneration() {
		return generation;
	}
	
	/**
	 * Recompute the field for one generation
	 */
	public void next(LifeField field) {
		setGeneration(generation + 1);
		LifeCell cell;
		
		/* Rules for cell state changes
		 * If alive with 2 or 3 neighbors: stay alive, else die
		 * If dead with 3 neighbors: come alive
		 */
		int neighbors;
		for (int r=0; r < field.rows; r++) {
			for (int c=0; c < field.cols; c++) {
				cell = field.get(r, c);
				neighbors = cell.aliveNeighbors(r);
				
				if (cell.isAlive()) {
					if ((neighbors > 3) || (neighbors < 2)) {
						cell.setState(false);
					}
				}
				else {
					if (neighbors == 3) {
						cell.setState(true);
					}
				}
				
				//System.out.println("> "+r+":"+c);
			}
		}
		
		/* Commit state changes made to cells
		 * For reasons why state changes are not immediate,
		 * please refer to LifeCell docstring
		 */
		for (int r=0; r < field.rows; r++) {
			for (int c=0; c < field.cols; c++) {
				field.get(r,c).commitState();
			}
		}
	}
	
	/**
	 * Reset the engine
	 */
	public void reset() {
		stop();
		setGeneration(0);
	}

	/**
	 * Start the simulation thread
	 * TODO
	 */
	public void start()
	{
	}

	/**
	 * Stop / pause the thread
	 * TODO
	 */
	public void stop()
	{
	}
	
}
