import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;
import javax.microedition.io.*;
import java.io.*;
import java.util.*;
import org.kxmlrpc.*;

/**
 * @author  Kyle Gabhart
 * @copyright  Kyle Gabhart © 2001
 * @version 1.0
 */
public class PopMidlet extends MIDlet implements CommandListener {
	private List					list;
	private Command				exitCommand;
	private String[]			menuItems;
	private Display				display;
	private Alert					response;
	private XmlRpcClient	xmlrpc;
	private Vector				params;
	
	public PopMidlet()
	{
		//Initialize the User Interface
		menuItems = new String[] {"US Population", "World Population"};
		list = new List( "Select a query", List.IMPLICIT, menuItems, null );
		exitCommand = new Command( "Exit", Command.EXIT, 1 );
		response = new Alert( "Service Return", null, null, AlertType.INFO );
		response.setTimeout( Alert.FOREVER );
		
		//Add commands
		list.addCommand( exitCommand );
		list.setCommandListener( this );
		
		//Obtain a reference to the device's UI
		display = Display.getDisplay( this );
	}//end PopMidlet()
	
	public void startApp()
	{
		display.setCurrent( list );
	}//end startApp()
	
	public void pauseApp() {}//end pauseApp()
	
	public void destroyApp( boolean unconditional )
	{
		//clean up
		list = null;
		exitCommand = null;
		display = null;
	}//end destoryApp( boolean )
	
	public void commandAction( Command com, Displayable dis )
	{
		if( dis == list && com == List.SELECT_COMMAND ) {
			switch( list.getSelectedIndex() ) {
				case 0:
					popCheck( new Boolean( false ) );
					break;
				case 1:
					popCheck( new Boolean( true ) );
					break;
			}//end switch( list.getSelectedIndex() )
		} else if ( com == exitCommand ) {
        		destroyApp( true );
        		notifyDestroyed();
		}//end if( dis == list && com == List.SELECT_COMMAND )
	}//end commandAction( Command, Displayable )
	
	private void popCheck( Boolean world )
	{
		String	population;
		
		try
    {
        xmlrpc = new XmlRpcClient( "http://www.wsjug.org/servlet/XmlRpcServlet" );
        params = new Vector();
        params.addElement( world );
        population = (String) xmlrpc.execute( "pop.getPop", params );
        response.setString( "The current estimated population of the " + ( world.booleanValue() ? "world" : "US" ) + " is " + population );
        display.setCurrent( response );
    } 
    catch ( Exception ex )
    {
        ex.printStackTrace();
    }//end try/catch
	}//end popCheck( Boolean )
}//end class PopMidlet