package com.one;

import javax.microedition.lcdui.*;

public class Renderer extends Canvas
{
	protected PaintableObject current;
	protected boolean shown, fsmode;

	protected Graphics prevgraphics;
	protected ExtGraphics extgraphics;

	protected static Display vibraDisplay;
	protected static int vibraDuration;
	
	public Renderer()
	{
		setFullScreenMode(fsmode = true);
		shown = false;

		current = new PaintableObject()		
		{
			public void paint(ExtGraphics g)
			{
			}
		};
	}
	
	public void setCurrent(PaintableObject po)
	{
		if(shown)
		{
			current.hideNotify();
			po.showNotify();
		}
		
		current = po;
		
		repaint();
		serviceRepaints();
	}
	
	public PaintableObject getCurrent()
	{
		return current;
	}
	
	public void repaint(PaintableObject po)
	{
		if(current == po)
		{
			repaint();
		}
	}
	
	public void repaint(PaintableObject po, int x, int y, int width, int height)
	{
		if(current == po)
		{
			repaint(x, y, width, height);
		}
	}
	
	public void serviceRepaints(PaintableObject po)
	{
		if(current == po)
		{
			serviceRepaints();
		}
	}
	
	public void setFullScreenMode(PaintableObject po, boolean mode)
	{
		setFullScreenMode(fsmode = mode);
	}
	
	public void paint(Graphics g)
	{
		if(g != prevgraphics)
		{
			extgraphics = new ExtGraphics(prevgraphics = g);
		}
		
		current.paint(extgraphics);
	}
	
	public void showNotify()
	{
		setFullScreenMode(fsmode);
		
		current.showNotify();
		shown = true;
	}
	
	public void hideNotify()
	{
		current.hideNotify();
		shown = false;
	}

	public boolean isShown()
	{
		return shown;
	}
	
	public void keyPressed(int keyCode)
	{
		vibrate();
		current.keyPressed(keyCode);
	}
	
	public void keyRepeated(int keyCode)
	{
		vibrate();
		current.keyRepeated(keyCode);
	}
	
	public void keyReleased(int keyCode)
	{
		current.keyReleased(keyCode);
	}
	
	public void pointerPressed(int x, int y)
	{
		vibrate();
		current.pointerPressed(x, y);
	}
	
	public void pointerDragged(int x, int y)
	{
		current.pointerDragged(x, y);
	}
	
	public void pointerReleased(int x, int y)
	{
		current.pointerReleased(x, y);
	}

	public static void setVibraDisplay(Display d)
	{
		vibraDisplay = d;
	}

	public static void setVibraDuration(int value)
	{
		vibraDuration = value;
	}

	public static void vibrate()
	{
		if(vibraDisplay != null && vibraDuration > 0)
		{
			vibraDisplay.vibrate(vibraDuration);
		}
	}
}
