import javax.microedition.lcdui.*;
import javax.microedition.midlet.*;
import java.util.Timer;
import java.util.TimerTask;

public class FishMidlet extends MIDlet implements CommandListener {
	public static FishMidlet m_midlet;

	private static Display m_display;
	private static FishGameCanvas m_canvas;

	public FishMidlet() {
		m_canvas = new FishGameCanvas();
		System.out.println("Canvas = "+m_canvas);
	}

	protected void startApp() throws MIDletStateChangeException {
		m_midlet = this; //save for getMidlet()
		if (m_display == null) {
			m_display = Display.getDisplay(this);
			m_display.setCurrent(m_canvas);
		}
		if (!m_canvas.start()) {
			showError("Failed to initialize.");
			return;
		}
	}

	protected void pauseApp() {
		if (m_canvas != null) {
			m_canvas.stop();
		}
	}

	protected void destroyApp(boolean flag) throws MIDletStateChangeException {
		if (m_canvas != null) {
			m_canvas.exit();
		}
	}

	public void showError(String sError) {
		Alert a = new Alert(null, sError, null, AlertType.ERROR);
		Display.getDisplay(this).setCurrent(a);
		TimerTask task =
			new TimerTask() {
				public void run() {
					FishMidlet.m_midlet.exit();
				}
			};
		Timer t = new Timer();
		t.schedule(task, 3000);
	}

	public void exit() {
		try {
			destroyApp(true);
		}
		catch (Exception e) {
		}
		notifyDestroyed();
	}

	//--------------------------------------------------------------------------
	// Game Command handling
	//--------------------------------------------------------------------------
	private Command m_cmdExit = new Command ("Exit", Command.EXIT, 1);
	private Command m_cmdPause = new Command ("Pause", Command.OK, 2);
	private Command m_cmdPlay = new Command ("Play", Command.OK, 2);

	//CommandListener
	public void commandAction (Command cmd, Displayable d) {
		if (cmd == m_cmdExit) {
			exit();
		}
		else if (cmd == m_cmdPause) {
			m_canvas.removeCommand(m_cmdPause);
			m_canvas.addCommand(m_cmdPlay);
			m_canvas.m_isPaused = true;
		}
		else if (cmd == m_cmdPlay) {
			m_canvas.removeCommand(m_cmdPlay);
			m_canvas.addCommand(m_cmdPause);
			m_canvas.m_isPaused = false;
		}
	}
}
