import java.util.Collection;
import java.util.Iterator;
import java.util.Random;

import de.tu_darmstadt.tk.SmartHomeNetworkSim.control.Controller;
import de.tu_darmstadt.tk.SmartHomeNetworkSim.core.NetworkManipulationAlgorithm;
import de.tu_darmstadt.tk.SmartHomeNetworkSim.core.SmartDevice;

/**
 * NetworkManipulationAlgorithm, lets the SmartDevices wiggle during the simulation.
 *
 * @author Andreas T. Meyer-Berg
 */
public class RandomWiggle implements NetworkManipulationAlgorithm {
	/**
	 * Random number generator
	 */
	private Random rand = new Random();
	
	@Override
	public void runAlgorithm(Controller controller, long currentTimeStep) {
		/**
		 * Visible devices of the model, to select one which should be moved
		 */
		Collection<SmartDevice> devices = controller.getNetworkController().getVisibleSmartDevices();
		/**
		 * Iterator for the devices
		 */
		Iterator<SmartDevice> it = devices.iterator();
		/**
		 * SmartDevice which should be moved
		 */
		SmartDevice move = null;
		/**
		 * Index of the randomly selected device
		 */
		int deviceNumber = rand.nextInt(devices.size());
		for(int i = 0; i <= deviceNumber && it.hasNext(); i++){
			move = it.next();
		}
		/**
		 * Move device randomly up to 5 pixels in x and y direction
		 */
		if(move != null){
			controller.getNetworkController().moveSmartDevice(move,(int)(move.getX()+rand.nextInt(11)-5), (int)(move.getY()+rand.nextInt(11)-5), move.getZ());
			controller.getNetworkController().validateDevicePosition();
		}
		/**
		 * Refresh Panel
		 */
		controller.notifyObservers();
	}

}