/*
 * Copyright (c) 2005-2010 KOM � Multimedia Communications Lab
 *
 * This file is part of PeerfactSim.KOM.
 * 
 * PeerfactSim.KOM is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * any later version.
 * 
 * PeerfactSim.KOM is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with PeerfactSim.KOM.  If not, see <http://www.gnu.org/licenses/>.
 *
 */

package de.tud.kom.p2psim.impl.energy;

import de.tud.kom.p2psim.api.energy.ComponentType;
import de.tud.kom.p2psim.api.energy.EnergyComponent;
import de.tud.kom.p2psim.api.energy.EnergyEventListener;
import de.tud.kom.p2psim.api.energy.EnergyState;
import de.tudarmstadt.maki.simonstrator.api.Time;


public class ActuatorEnergyComponent implements EnergyComponent {
	
	/**
	 * States supported by this energy component
	 */
	public final EnergyState OFF, HOVER, FLY;
	
	private EnergyState currentState;
	
	private EnergyEventListener energyModel;
	
	private long lastStateChange;
		
	public ActuatorEnergyComponent(int numberOfActuators, double volt, double hoverAmp, double flyAmp) {
		OFF = new DefaultEnergyState("OFF", 0);
		HOVER = new DefaultEnergyState("HOVER", numberOfActuators * (hoverAmp * volt) * 1000000);
		FLY = new DefaultEnergyState("FLY", numberOfActuators * (flyAmp * volt) * 1000000);
		
		this.currentState = OFF;
		this.lastStateChange = Time.getCurrentTime();
	}
	
	public void doStateChange(EnergyState newState) {
		
		if(energyModel.turnOn(this) || newState.equals(OFF))
		{
			long timeSpentInState = Time.getCurrentTime() - lastStateChange;
			
			energyModel.switchedState(this, currentState, newState,
					timeSpentInState);
			currentState = newState;		
			lastStateChange = Time.getCurrentTime();
		}		
	}
	
	@Override
	public void eventOccurred(Object content, int type) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public ComponentType getType() {	
		return ComponentType.ACTUATOR;
	}

	@Override
	public void turnOff() {
		if(!currentState.equals(OFF)) {			
			doStateChange(OFF);
		}		
	}

	@Override
	public boolean turnOn() {
		if (energyModel.turnOn(this)) {
			if (!currentState.equals(HOVER)) {
				doStateChange(HOVER);
			}
			return true;
		}
		return false;
	}
	
	public boolean isAvailable() {
		return energyModel.turnOn(this);
	}

	@Override
	public boolean isOn() {
		return (!currentState.equals(OFF) && energyModel.turnOn(this));
	}

	@Override
	public void setEnergyEventListener(EnergyEventListener listener) {
		energyModel = listener;		
	}

	public EnergyState getCurrentState()
	{
		return currentState;
	}
}
