import javax.microedition.midlet.MIDlet;
import javax.microedition.midlet.MIDletStateChangeException;

import org.eclipse.ercp.swt.mobile.MobileShell;
import org.eclipse.swt.SWT;
import org.eclipse.swt.layout.FillLayout;
import org.eclipse.swt.widgets.Display;


/**
 * Clase principal de un Midlet que use eSWT. 
 * Esta clase no hace nada más que crear el display y el shell, pero no añade comandos . POr ejemplo
 * no tiene comandos para salir.
 * Para crear cualquier aplicación se puede crear una clase que derive de esta e implementar
 * ya en ella los detalles manejando la shell y el display
 * 
 * @author luis
 *
 */
public abstract class Main extends MIDlet implements Runnable {

	private Thread thread;
	protected Display display;
	protected MobileShell shell;
	
	protected void startApp() throws MIDletStateChangeException {
		if (thread == null) {
			thread = new Thread(this);
			thread.start();
		}
	}
	
	public abstract void play();

	public void run() {
		display = new Display();
		shell = new MobileShell(display, SWT.NONE, 2);
		shell.open();
		try {
			play();
		} catch(Exception e) {
			System.out.println("Error " + e);
			display.dispose();
			notifyDestroyed();
			return;
		}
		
		try {
			while (!shell.isDisposed()) {
				if (!display.readAndDispatch())
					display.sleep();
			}
		} finally {
			display.dispose();
			notifyDestroyed();
		}
	}

	protected void pauseApp() {
		// do nothing
	}

	protected void destroyApp(boolean unconditional)
			throws MIDletStateChangeException {
		display.asyncExec(new Runnable() {
			public void run() {
				if (!shell.isDisposed())
					shell.close();
			}
		});
	}

}

