/*
 * 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.topology.movement.modularosm.groups.groupencounter;

import de.tud.kom.p2psim.api.scenario.ConfigurationException;
import de.tud.kom.p2psim.impl.topology.movement.modularosm.groups.SocialMovementGroup;
import de.tudarmstadt.maki.simonstrator.api.Time;
import de.tudarmstadt.maki.simonstrator.api.util.XMLConfigurableConstructor;


/**
 * This class checks if there is any pair of groups which encounter each other. Randomly decides
 * if the groups wait for a specified of time during encounter or not.
 * 
 * @author Marcel Verst
 * @version 1.0, 22.11.2018
 */
public class Wait extends AbstractGroupEncounter{
	//--- VARIABLES TO BE DECLARED IN CONFIG ---
	protected double probabilityToWait;
	protected long timeToWait;
	//------------------------------------------

	@XMLConfigurableConstructor({"enableGroupEncounters","groupEncounterMeetingDistance","groupReencounterWaitTime"})
	public Wait(boolean enableGroupEncounters,
			double groupEncounterMeetingDistance,
			long groupReencounterWaitTime) {
		super(enableGroupEncounters, groupEncounterMeetingDistance,
				groupReencounterWaitTime);		
	}
	
	@Override
	public void handleGroupEncounter(SocialMovementGroup group1, SocialMovementGroup group2) {
		if(decide() == DECISION_WAIT) {
			long waittime = getRandomWaitTime();
			wait(group1, waittime);
			wait(group2, waittime);
		}
	}

	protected long getRandomWaitTime() {
		return (long) (rand.nextDouble() * (timeToWait + 1 - Time.MINUTE ) + Time.MINUTE);
		
	} 
	
	/*
	 * GETTERS AND SETTERS
	 */
	public void setProbabilityToWait(double probabilityToWait) {
		if (probabilityToWait < 0 || probabilityToWait > 1.0) {
			throw new ConfigurationException(
					"probabilityToWait should be between 0.0 and 1.0!");
		}
		this.probabilityToWait = probabilityToWait;
	}

	public void setTimeToWait(long timeToWait) {
		if(timeToWait < 0) {
			throw new ConfigurationException(
					"timeToWait should be greater or equal than 0!");
		}
		this.timeToWait = timeToWait;
	}

	@Override
	protected int decide() {
		// mergePartially
		if(rand.nextDouble() < probabilityToWait) {
			return DECISION_WAIT;
		}		
		else 
			return DECISION_NONE;
	}
}
