/*
 * 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.impl.topology.movement.modularosm.groups.SocialMovementGroup;
import de.tudarmstadt.maki.simonstrator.api.Time;
import de.tudarmstadt.maki.simonstrator.api.util.XMLConfigurableConstructor;


/**
 * 
 * @author Julian Zobel
 * @version 1.0, 04.02.2020
 */
public class WaitSmartMerge extends Wait{

	@XMLConfigurableConstructor({"enableGroupEncounters","groupEncounterMeetingDistance","groupReencounterWaitTime"})
	public WaitSmartMerge(boolean enableGroupEncounters,
			double groupEncounterMeetingDistance,
			long groupReencounterWaitTime) {
		super(enableGroupEncounters, groupEncounterMeetingDistance,
				groupReencounterWaitTime);		
	}
	
	@Override
	public void handleGroupEncounter(SocialMovementGroup group1, SocialMovementGroup group2) {
		
		long pauseTime = getRandomWaitTime();
		
		if(groupCon.waitingGroups.containsKey(group1) && !groupCon.waitingGroups.containsKey(group2)) {
			pauseTime = getRemainingGroupWaitTime(group1);
		}
		else if(!groupCon.waitingGroups.containsKey(group1) && groupCon.waitingGroups.containsKey(group2)) {
			pauseTime = getRemainingGroupWaitTime(group2);		
		}
		
		
		if(group1.getLeader().getCurrentTargetAttractionPoint() == group2.getLeader().getCurrentTargetAttractionPoint()) {			
			SocialMovementGroup merged = mergeGroupsFully(group1, group2);
			wait(merged, pauseTime);
		}		
		else if(decide() == DECISION_WAIT) {			
			wait(group1, pauseTime);
			wait(group2, pauseTime);
		}		
	}
	
	private long getRemainingGroupWaitTime(SocialMovementGroup group) {		
		 long pausetime = groupCon.waitingGroups.get(group).getA();		 
		 long issueTime = groupCon.waitingGroups.get(group).getB();
		 return issueTime + pausetime - Time.getCurrentTime();
	}
}


