package express.awt;

import express.lines.*;
import java.awt.*;
import java.awt.event.*;
import java.util.*;

public class RedrawingCanvas extends Canvas {
	
	private final static int DELAY = 100; //msec
	public Vector v = new Vector(); //vector of line objects (RedrawableLines)
		
	Image offImage;
	Graphics offGraphics;
	AnimThread theThread;

	Image offImageStatic;
	Graphics offGraphicsStatic;

	public RedrawingCanvas() {		
		theThread = new AnimThread();
		theThread.start();
	}

	public void addRedrawableLine(RedrawableLine r) {
		v.addElement(r);
	}

	public void paint(Graphics g) {
		g.drawImage(offImage, 0, 0, this);
	}

	public void erase() {
		offGraphics.setColor(Color.black);
		offGraphics.fillRect(0,0,this.getSize().width,this.getSize().height);
		offGraphics.drawImage(offImageStatic, 0, 0, this);
	}
	
	public void update(Graphics g) {
		if (offImage == null || offImage.getWidth(this) != this.getSize().width || offImage.getHeight(this) != this.getSize().height) {
			offImage = createImage(this.getSize().width,this.getSize().height);
			offGraphics = offImage.getGraphics();
		}
		if (offImageStatic == null || offImageStatic.getWidth(this) != this.getSize().width || offImageStatic.getHeight(this) != this.getSize().height) {
			offImageStatic = createImage(this.getSize().width,this.getSize().height);
			offGraphicsStatic = offImageStatic.getGraphics();
		}
		erase();

		for (int i = 0, len = v.size(); i < len; ++i) {		
			if ( ((RedrawableLine)v.elementAt(i)).living() ) 
				((RedrawableLine)v.elementAt(i)).redraw(offGraphics);
			else 	{
				((RedrawableLine)v.elementAt(i)).redraw(offGraphicsStatic);
				v.removeElementAt(i);
			}
		}
		paint(g);
	}
					

	private class AnimThread extends Thread {
		
		public void run() {
			try {
				while (true) {
					Thread.sleep(DELAY);
					repaint();
				}
			}
			catch (InterruptedException e)
			{e.printStackTrace();}
		}
	}
	
	public Dimension getPreferredSize() {
		return new Dimension(400, 400);
	}
	
}


