/*
 * LocationApp.java
 *
 * Created on 25 febbraio 2005, 20.32
 */
import javax.microedition.io.*;
import javax.microedition.lcdui.*;
import javax.microedition.midlet.*;
import com.motorola.location.*;

/**
 *
 * @author Enrico
 */
public class LocationApp extends MIDlet implements CommandListener
{    
    PositionSource lcon;
    Command ec = null;
    Command ok = null;
    Display dsp = null;
    LocCanvas lc = null;
    Form inp = new Form("Settings");
    TextField tTimeout, tAccuracy, tAge;
    /** Creates a new instance of LocationApp */
    public LocationApp()
    {
        
    }
    
    protected void destroyApp(boolean unconditional)
    {
        if (lc!=null) lc.bTerminate = true;
        try {lc.loct.join();} catch (Exception e) {}
    }
    
    protected void pauseApp()
    {
    }
    
    protected void startApp()
    {
        dsp = Display.getDisplay(this);
        ok = new Command("Start",Command.SCREEN,1);
        ec = new Command("Exit",Command.SCREEN,2);

        tAccuracy = new TextField("Accuracy (meters)", "500", 4, TextField.DECIMAL);
        tTimeout = new TextField("Timeout (millisec.) (0=default)","0", 5, TextField.DECIMAL);
        tAge = new TextField("Age (millisec.)","1",5,TextField.DECIMAL);
        inp.append("EmGPS " + this.getAppProperty("MIDlet-Version") + "\n");        
        inp.append(tAccuracy);
        inp.append(tTimeout);
        inp.append(tAge);
        inp.setCommandListener(this);
        inp.addCommand(ok);
        inp.addCommand(ec);
        dsp.setCurrent(inp);
        
        
    }
    
    public void commandAction(Command cmd, Displayable d)
    {
        if (cmd == ec)
        {
            destroyApp(true);
            notifyDestroyed();
        }
        else if (cmd == ok)
        {            
            boolean err;
            lcon = null;

            try
            {
                lcon = (PositionSource) Connector.open("location://");
                err=false;
            }
            catch (Exception e)
            {
                err=true;
            }

            lc = new LocCanvas(lcon,Integer.valueOf(tAccuracy.getString()).intValue(), Integer.valueOf(tTimeout.getString()).intValue(), Integer.valueOf(tAge.getString()).intValue());;
            lc.setCommandListener(this);
            lc.addCommand(ec);
            lc.bInstantiationError=err;

            dsp.setCurrent(lc);

            if (lcon!=null)
            {
                lcon.addPositionListener(lc);
                lc.loct.start();
            }
        }
    }    
}
