package simogl.resource;

import simogl.gameobjects.AbstractGameObject;
import simogl.gameobjects.building.AbstractBuilding;
import simogl.gameobjects.building.Farm;
import simogl.gameobjects.building.House;
import simogl.gui.ResourcePanel;
import simogl.level.AbstractLevel;

/**
 * Represents the resource "food"
 * @author Frank Bruns
 *
 */
public class Food extends AbstractResource
{
	/**
	 * Creates an object of the resource food with the specified
	 * initial amount
	 * @param amount initial amount of food
	 * @param intervall intervall of time in miliseconds in which
	 * calculations on resources will be performed, effecting the
	 * amount of the player's resources
	 */
	public Food(int amount, long intervall)
	{
		super(amount,intervall);
	}

	@Override
	public void update(long elapsedTime)
	{
		this.cumulatedTime += elapsedTime;
		
		if(this.cumulatedTime > this.getUpdateIntervall())
		{
			// reset cumulated time first
			this.cumulatedTime = 0L;	
			
			int totalProduction = 0;
			int totalConsumption = 0;
			
			AbstractBuilding building = null;
			for(AbstractGameObject b : AbstractLevel.buildings)
			{
				 building = (AbstractBuilding)b;				 				 
				 
				 // consider food production & consumption of some buildings
				 if(building.getType() == AbstractBuilding.FARM)
				 {
					 Farm farm = (Farm)building;
					 totalProduction += farm.getFoodProduction();					 
				 }
				 if(building.getType() == AbstractBuilding.HOUSE)
				 {
					 House house = (House)building;
					 totalConsumption += house.getFoodConsumption();
				 }
			}
				 
			// add produced food to the resources
			this.setCurrentAmount(this.getCurrentAmount() + totalProduction);
			
			 // subtract consumed food and take care that 
			// the value for food can't fall below 0
			if(this.getCurrentAmount()-totalConsumption >= 0)
			{
				this.setCurrentAmount(this.getCurrentAmount() - totalConsumption); 
			}
			else this.setCurrentAmount(0);
			
			
			ResourcePanel.setLabelFood(Integer.toString(this.getCurrentAmount()));
		}
	}
}