import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.KeyEventDispatcher;
import java.awt.KeyboardFocusManager;
import java.awt.image.BufferedImage;
import javax.swing.JComponent;
public abstract class HWMainDisplay extends JComponent implements Runnable {
	int speed = 40;	//in fps
	BufferedImage[] buffers = new BufferedImage[2];
	int bufferI;
	int imgSize;
	BufferedImage screen;
	HWDisplay frame;
	KeyEventDispatcher ked;
	private boolean running;
	
	public HWMainDisplay(HWDisplay inFrame) {
		this.setPreferredSize(new Dimension(512,512));
		bufferI = 0;
		imgSize = getImgSize();
		buffers[0] = new BufferedImage(imgSize,imgSize,BufferedImage.TYPE_INT_RGB);
		buffers[1] = new BufferedImage(imgSize,imgSize,BufferedImage.TYPE_INT_RGB);
		frame = inFrame;
	}
	public void stop() {
		KeyboardFocusManager.getCurrentKeyboardFocusManager().removeKeyEventDispatcher(ked);
		running = false;
	}
	public void run() {
		KeyboardFocusManager.getCurrentKeyboardFocusManager().addKeyEventDispatcher(ked);
		long tm = System.currentTimeMillis();
		int msPerFrame = 1000/speed;
		running=true;
		while (running) {
			update(buffers[bufferI]);
			screen = buffers[bufferI];
			bufferI = (bufferI+1)%2;
			frame.repaint();
			try {
				tm += msPerFrame;
				Thread.sleep(Math.max(0, tm - System.currentTimeMillis()));
			} catch (InterruptedException ex) {
				break;
			}
		}
	}
	protected abstract int getImgSize();
	protected abstract void update(BufferedImage img);
	protected void paintComponent(Graphics g) {
		g.drawImage(screen, 0, 0, 512, 512, 0, 0, imgSize, imgSize, null);
	}
}
