/**
 * 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/
 */

import java.awt.GridLayout;
import javax.swing.JPanel;

/**
 * This is the playing Field for the Life Game.
 * 
 * It is responsible for setting up the field and creating
 * all of the cells that populate that field.
 * 
 * NOTE: All generation computations are made by the simulation engine.
 */
public class LifeField
{
	JavaLife parent;
	LifeCell[][] cells;
	int rows = 20;
	int cols = 20;
	// My gui representation lives inside this panel
	JPanel field;
	
	public LifeField(JavaLife parent) {
		this.parent = parent;
	}
	
	public void create(int rows, int cols) {
		if (rows > 0) this.rows = rows;
		if (cols > 0) this.cols = cols;
		createField();
		createFieldGUI();
	}
	
	/**
	 * Create a 2D array of life cells.
	 */
	public void createField() {
		cells = new LifeCell[rows][cols]; 
		LifeCell cell;
		for (int r=0; r < rows; r++) {
			for (int c=0; c < cols; c++) {
				cell = new LifeCell(false);
				cells[r][c] = cell;
			}
		}
		
		/*
		 * Tell each cell who his neighbors are.
		 * I did it this way becuase i figured it would speed up the 
		 * generational computations if each cell could simply examine
		 * the state of a pre-computed list neighbors rather than
		 * have to re-compute who his neighbors were at every generation.
		 */
		for (int r=0; r < rows; r++) {
			for (int c=0; c < cols; c++) {
				// For each element around this cell...
				for (int up=-1; up<=1; up++) {
				for (int left=-1; left<=1; left++) {
					if ((up == 0) && (left == 0)) continue;
					if ((r+up < 0) || (r+up >= rows)) continue;
					if ((c+left < 0) || (c+left >= cols)) continue;
					//System.out.println(r+","+c+" add neighbor "+newr+","+newc);
					cells[r][c].addNeighbor(cells[r+up][c+left]);
				}
				}
			}
		}
	}
	
	/**
	 * Put all the cells of this field into a JPanel.
	 */
	public void createFieldGUI() {
		field = new JPanel(new GridLayout(rows, cols));
		for (int r=0; r < rows; r++) {
			for (int c=0; c < cols; c++) {
				field.add(cells[r][c]);
			}
		}
	}

	public JPanel getFieldGUI() {
		return field;
	}

	/**
	 * Reset all cells on this field.
	 */
	public void reset() {
		for (int r=0; r < rows; r++) {
			for (int c=0; c < cols; c++) {
				cells[r][c].reset();
				//System.out.println("reset "+r+","+c);
			}
		}
	}
	
	/**
	 * Get the cell at these coords
	 */
	public LifeCell get(int row, int col) {
		return cells[row][col];
	}

}

