package ls.graph.script;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import ls.graph.Controller;
import ls.script.Scriptable;
import ls.util.Utils;
public class Algorithm implements Scriptable, Runnable
{
private List<AlgorithmStep> steps = null;
private int delay = 1000; //in ms
private List<AlgorithmListener> listeners = null;
private boolean stop;
public Algorithm()
{
super();
this.steps = new ArrayList<AlgorithmStep>();
this.listeners = new LinkedList<AlgorithmListener>();
String sDelay = Controller.getProperty("ALGORITHM_STEP_DELAY", String.valueOf(this.delay));
try
{ this.delay = Integer.parseInt(sDelay); }
catch (NumberFormatException exn)
{ Utils.exn(exn); }
}
public synchronized void addListener(AlgorithmListener l)
{
if (l != null) this.listeners.add(l);
}
private void fireExecutionStarted()
{
for (AlgorithmListener l : this.listeners)
{
l.executionStarted(this);
}
}
private void fireExecutionEnded()
{
for (AlgorithmListener l : this.listeners)
l.executionEnded(this);
}
private void fireStepStarted(int ind)
{
for (AlgorithmListener l : this.listeners)
l.startingStep(ind);
}
public String getBindingName()
{
return "Algorithm";
}
public void addStep(AlgorithmStep step)
{
if (step != null)
this.steps.add(step);
}
public void run()
{
fireExecutionStarted();
stop = steps.size() <= 0;
int nextStepIndex = 0;
while (!stop)
{
AlgorithmStep nextStep = steps.get(nextStepIndex);
if (nextStep != null)
{
fireStepStarted(nextStepIndex);
stop = nextStep.execute();
if (!stop)
{
nextStepIndex = nextStep.getNextStep();
try
{
synchronized (this)
{ this.wait(getDelay()); }
}
catch (InterruptedException exn)
{
Utils.exn(exn);
}
}
}
else stop = true; //no next step
}
fireExecutionEnded();
}
public void setStop(boolean st)
{
this.stop = st;
}
//private Random random = new Random();
private int getDelay()
{
return this.delay;
//int d = random.nextInt(delay);
//d = Math.max(d/4, d);
//return d;
}
}