package Life;

/**
 * This type was created by Jens Elbęk
 */
public class Cell 
{
	CellLocation location;
	static boolean dead = false, living = true;
	

	boolean nextstate=living;
	boolean alive = dead;
	boolean previus_state = dead;

	int pixelIndex;
	/**
 * This is the ecological system the cell belongs
*/
	public EcologicalSystem eath;
/**
 * Cell constructor comment.
 */
public Cell(EcologicalSystem parmeath, CellLocation parmlocation) 
{
	super();
	eath = parmeath;
	location = parmlocation;
	alive = dead;
	pixelIndex = (location.y * location.x) + location.x;
}
/**
 * This method was created by Jens Elbęk
 */
public boolean cellIsAlive() 
{
	return alive;
}
/**
 * Insert the method's description here.
 * Creation date: (16-04-01 20:04:22)
 */
public void draw(int[] pixels)
{
	int startlocation = ( (eath.pointsize*location.y) * (eath.pointsize*eath.bredde) ) + (location.x*eath.pointsize);

	int i = 0, color=0, s = startlocation;
	if (alive)
		color = eath.foreground;
	else
		color = eath.background;

	for (int h=0; h < eath.pointsize; h++)
	{
		s = startlocation+ (eath.bredde*eath.pointsize*h);
		for (int l=0; l < eath.pointsize; l++)
		{
			i = (s+l);
			pixels[i] = color;
/*			if (i == 916)
			{
				System.out.println("Lifecount=" + eath.lifecount + "startlocation=" + startlocation);
				System.out.println("=========> x=" + location.x + " y=" + location.y + " giver index=" + i + " color=" + color);
				System.out.println("=========> startlocation=" + s + "  h=" + h + " l=" + l);
			}
*/		}	
		
	}	
}
/**
 * This method was created by Jens Elbęk
 */
public boolean kill() 
{
	if (nextstate != dead)
	{
		nextstate = dead;
		return true;
	}
	return false;
}
/**
 * 
 * Creation date: (02-04-01 21:38:00)
 * @return int
 */
public int neighboursAlive() 
{
	int n = 0, x = 0, y = 0;
	for (int i = 0; i < location.direction.length; i++)
	{
		x = location.x + location.direction[i][0];
		y = location.y + location.direction[i][1];
		if ( x < 0 || y < 0 || x > eath.xMax || y > eath.yMax)	// If the location is out in space
		{
		// then its considered dead
			continue;
		}
		if (eath.cells[x][y].alive)
		{
			n++;
		}	
	}
	
	
	return n;
}
/**
 * This method was created by Jens Elbęk
 */
public boolean setAlive() 
{
	if (nextstate != living)
	{
		nextstate = living;
		return true;
	}
	return false;
}
/**
 * Returns a String that represents the value of this object.
 * @return a string representation of the receiver
 */
public String toString() 
{
	String text = new String("Cell at " 
		+ location.x 
		+ ","
		+ location.y
		+ " is ");
	if (cellIsAlive())
		text = text + "living";
	else
		text = text + "dead";
	return text;
}
}

