package animation;

import java.awt.event.ComponentEvent;
import java.awt.event.ComponentListener;

import javax.swing.JFrame;
import javax.swing.JTree;
import javax.swing.SwingUtilities;

import graph.LayeredGraphNode;

public abstract class AnimatedAlgorithm extends Thread implements AlgorithmStage {

	protected AnimationController ac;
	protected LayeredGraphNode graph;
	private JFrame view;
	
	public AnimatedAlgorithm( AnimationController controller, LayeredGraphNode graph, JFrame view )
	{
		this.ac = controller;
		this.graph = graph;
		this.view = view;
	}
	
	private void update()
	{
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                view.repaint();
                for( ComponentListener l : view.getComponentListeners() )
                {
                    l.componentResized( new ComponentEvent(view, 0) );
                }
            }
        });
	}
	
	@Override
	public void run()
	{
		while( true ) // if this loop would end we could not undo steps any more
		{
			try {
				switch( ac.getNextAction() )
				{
				case FORWARD:
					forwardStep();
					update();
					break;
                case FORWARD_OUT:
                    forwardStepOut();
                    graph.unselectGraph();
                    update();
                    break;
                case FORWARD_OVER:
                    forwardStepOver();
                    graph.unselectGraph();
                    update();
                    break;
				case BACKWARD:
					backwardStep();
                    update();
					break;
                case BACKWARD_OUT:
                    backwardStepOut();
                    graph.unselectGraph();
                    update();
                    break;
                case BACKWARD_OVER:
                    backwardStepOver();
                    graph.unselectGraph();
                    update();
                    break;
                default:
                    break;
				}
			} catch (InterruptedException e) {
				e.printStackTrace();
				return;
			}
			
		}
	}
	
    public abstract PseudoCodeNode createPseudocodeTree( JTree tree );
}
