/*
 * 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 java.util.List;
import java.util.Random;
import java.util.Vector;

import de.tud.kom.p2psim.api.common.SimHost;
import de.tud.kom.p2psim.api.energy.Battery;
import de.tud.kom.p2psim.api.energy.EnergyConfiguration;
import de.tud.kom.p2psim.api.energy.EnergyModel;
import de.tud.kom.p2psim.api.scenario.ConfigurationException;
import de.tud.kom.p2psim.impl.energy.models.ComponentBasedEnergyModel;
import de.tudarmstadt.maki.simonstrator.api.Host;
import de.tudarmstadt.maki.simonstrator.api.Monitor;
import de.tudarmstadt.maki.simonstrator.api.Monitor.Level;
import de.tudarmstadt.maki.simonstrator.api.Randoms;
import de.tudarmstadt.maki.simonstrator.api.component.HostComponentFactory;

/**
 * This factory creates and configures an {@link EnergyModel} and its
 * components. Again, we use the LinkLayer-model of configuration presets to
 * ensure a proper configuration and integration, where the model is not
 * configured itself but the user select a configuration that provides some
 * checking of the selected parameters.
 * 
 * @author Bjoern Richerzhagen
 * @version 1.0, 25.02.2012
 */
public class EnergyModelFactory implements HostComponentFactory {
	
	private Random random;

	/**
	 * A List of the currently active MAC-Layer configurations
	 */
	private List<EnergyConfiguration> energyConfigurations;

	/**
	 * This is used to reset configurations if a new Group of Hosts is to be
	 * configured. We imply that the Model is fully configured for each Group or
	 * not at all to keep the settings of the previous group. 
	 */
	private boolean configurationsUsed = false;
	
	private boolean useRandomBatteryStartConfiguration = false;
	private double minimumStartEnergyLevel = 0.3;
		
	
	private Battery batteryModel = new SimpleBattery(186480000, 186480000);

	/**
	 * A new Factory
	 */
	public EnergyModelFactory() {
		energyConfigurations = new Vector<EnergyConfiguration>();
		random = Randoms.getRandom(EnergyModelFactory.class);
	}

	@Override
	public EnergyModel createComponent(Host pHost) {
		SimHost host = (SimHost) pHost;
		if (energyConfigurations.isEmpty()) {
			throw new ConfigurationException(
					"No Components were specified within the EnergyModel!\n"
							+ "Add at least one child element <Component class=\"...\" /> pointing to an EnergyConfiguration.");
		}
		configurationsUsed = true;
		
		Battery bat;
		
		if(useRandomBatteryStartConfiguration)
		{
			// clone the battery from the provided model			
			double percentageOfFullBattery = (1 - random.nextDouble());
			if(percentageOfFullBattery < minimumStartEnergyLevel)
				percentageOfFullBattery = minimumStartEnergyLevel;
			double initialEnergy = batteryModel.getMaximumEnergy() * percentageOfFullBattery;
			
			bat = batteryModel.copy(initialEnergy);
		}
		else {			
			bat = batteryModel.copy(batteryModel.getMaximumEnergy());			
		}

		EnergyModel em = new ComponentBasedEnergyModel(host, bat);
		
		for (EnergyConfiguration config : energyConfigurations) {
			em.registerComponent(config.getConfiguredEnergyComponent(host));
		}
		return em;
	}

	/**
	 * Set the Battery model that is to be used in this simulation.
	 * 
	 * @param energy
	 */
	public void setBattery(Battery battery) {	
		this.batteryModel = battery;
	}

	/**
	 * Load a configuration for this ModelFactory
	 * 
	 * @param energyConfig
	 */
	public void setComponent(EnergyConfiguration energyConfig) {
		if (configurationsUsed) {
			energyConfigurations.clear();
			configurationsUsed = false;
		}
		// check configuration
		if (!energyConfig.isWellConfigured()) {
			throw new ConfigurationException(
					"The EnergyModel was not well configured.\n"
							+ energyConfig.getHelp());
		}
		// just log the information
		Monitor.log(EnergyModelFactory.class, Level.INFO,
				"EnergyModel created - some information:\n %s",
				energyConfig.getHelp());
		energyConfigurations.add(energyConfig);
	}

	public void setMinimumStartEnergyLevel(double level) {
		if(level > 1.0) {
			this.minimumStartEnergyLevel = 1.0;
		}
		else if(level < 0.0) {
			this.minimumStartEnergyLevel = 0.0;
		}
		else {
			this.minimumStartEnergyLevel = level;
		}
	}
	
	public void setUseRandomBatteryStartConfiguration(boolean randomStart) {
		this.useRandomBatteryStartConfiguration = randomStart;
	}

}
