package lpv.simulation;

import java.util.ArrayList;
import java.util.Iterator;

import lpv.simulator.Simulator;

public class SimulationThread extends Thread {
	
	private Simulation simulation;
	private Simulator simulator;
	private ArrayList<Runnable> handlers;
	private int delay;

	public SimulationThread(Simulator simulator, Simulation simulation, int delay) {
		this.simulator = simulator;
		this.simulation = simulation;
		this.handlers = new ArrayList<Runnable>();
		this.delay = delay;
	}
	
	public void addCompletionHandler(Runnable handler) {
		handlers.add(handler);
	}
	
	@Override
	public void run() {
		try {
			Iterator<SimulationStep> it = simulation.iterator();
			while(it.hasNext()) {
				SimulationStep step = it.next();
				step.run(simulator);
				if(it.hasNext()) {
					Thread.sleep(delay);
				}
			}
		} catch (InterruptedException e) {
			e.printStackTrace();
		} finally {
			for(Runnable handler : handlers) {
				handler.run();
			}
		}
	}
}
