// Test sample 3.

package oracle.wireless.me.sample1;

import java.util.*;

import javax.microedition.lcdui.*;
import javax.microedition.midlet.*;

import oracle.wireless.me.core.*;

/**
 * Sample3 calls methods in TestWebService to test parameters that
 * are vectors, hashes, and arrays.
 */
public class Sample3 extends MIDlet implements CommandListener
{
    private Display display;
    private Form form;
    private Command exitCommand;
    private Command vectorCommand;
    private Command hashCommand;
    private Command clearCCommand;
    private Command clearSCommand;
    private Command strArrCommand;
    private Command intArrCommand;
    private Command boolCommand;
    private Command intCommand;
    private Command dateCommand;

    private ServiceFactory serviceFactory;
    private Service service;

    public Sample3()
    {
    }

    protected void startApp() throws MIDletStateChangeException
    {
	    //ServiceManager.getInstance();
	    if (display == null) {
        initMIDlet();
	    }
    }

    protected void pauseApp()
    {
      try {
        ServiceManager.getInstance().close();
      }
      catch (Exception e) {
      }
      //System.out.println("Sample3 paused");
    }

    protected void destroyApp(boolean unconditional)
	      throws MIDletStateChangeException
    {
	    exitMIDlet();
    }

    public void commandAction(Command c, Displayable d)
    {
	    if (c == exitCommand) {
	      exitMIDlet();
	    }
	    else if (c == vectorCommand) {
	      testVector();
	    }
	    else if (c == hashCommand) {
	      testHashtable();
	    }
	    else if (c == clearCCommand) {
	      clearCache();
	    }
	    else if (c == clearSCommand) {
	      clearScreen();
	    }
	    else if (c == strArrCommand) {
	      testStringArray();
	    }
	    else if (c == intArrCommand) {
	      testIntArray();
	    }
	    else if (c == boolCommand) {
	      testBoolean();
	    }
	    else if (c == intCommand) {
	      testInteger();
	    }
	    else if (c == dateCommand) {
	      testDate();
	    }
    }

    private void initMIDlet()
    {
      // Get the URL of the J2ME proxy server.
      String servURL = getAppProperty("oracle-j2me-server-url");

      if (servURL == null) {
	      servURL = "http://localhost:7777/mcs/wsproxy/proxy";
	      //System.out.println("Unable to get j2me_proxy app property, using default: " + servURL);
      }

      serviceFactory = ServiceFactory.getInstance();
      service = serviceFactory.createService(servURL, "DEFAULT", "TestWebService");

      // Display, etc.
      display = Display.getDisplay(this);

      exitCommand = new Command("Exit", Command.EXIT, 1);
      vectorCommand = new Command("testVector", Command.SCREEN, 1);
      hashCommand = new Command("testHashtable", Command.SCREEN, 2);
      clearCCommand = new Command("Clear Cache", Command.SCREEN, 2);
      clearSCommand = new Command("Clear Screen", Command.SCREEN, 2);
      strArrCommand = new Command("testStringArray", Command.SCREEN, 2);
      intArrCommand = new Command("testIntArray", Command.SCREEN, 2);
      boolCommand = new Command("testBoolean", Command.SCREEN, 3);
      intCommand = new Command("testInteger", Command.SCREEN, 3);
      dateCommand = new Command("testDate", Command.SCREEN, 3);

      form = new SimpleForm();
      display.setCurrent( form );
    }

  // On exit from the midlet, clear cache.
  private void exitMIDlet()
  {
    clearCache();
    try {
      ServiceManager.getInstance().close();
    }
    catch (Exception e) {
    }

    notifyDestroyed();
  }


  private void testVector()
  {
    // Set cache timeout to 1 minute.
    Call call = service.createCall("testVector", 1);

    Vector param3 = new Vector();
    param3.addElement( new String("Vector test") );
    param3.addElement( new String("success") );

    // Put the parameters in a Vector.
    Vector params = new Vector();
    params.addElement( new Integer( 42 ) );
    params.addElement( new String("World") );
    params.addElement( param3 );

    Response res = makeCall( call, params );

    // Continue only if response is not null.
    if (res != null) {
      try {
	      Vector respVec = res.getVector();
	
	      // Display the result of the call.
	      form.append( respVec.toString() + "\n" );
      }
      catch (Exception e) {
	      // Display the error.
	      form.append( e.getMessage() + "\n" );
      }
    }
  }

  
  private void testHashtable()
  {
    // Set cache timeout to 1 minute.
    Call call = service.createCall("testHashtable", 1);

    Hashtable param3 = new Hashtable();
    param3.put( new String("Hashtable test"), new String("success") );

    // Put the parameters in a Vector.
    Vector params = new Vector();
    params.addElement( new Integer( 42 ) );
    params.addElement( new String("World") );
    params.addElement( param3 );

    Response res = makeCall( call, params );

    // Continue only if response is not null.
    if (res != null) {
      try {
	      Hashtable respHash = res.getHashtable();
	
	      // Display the result of the call.
	      form.append( respHash.toString() + "\n" );
      }
      catch (Exception e) {
	      // Display the error.
	      form.append( e.getMessage() + "\n");
      }
    }
  }
  

  private void testStringArray()
  {
    // Set cache timeout to 1 minute.
    Call call = service.createCall("testStringArray", 1);

    String[] strArr = new String[ 2 ];
    strArr[0] = new String("First");
    strArr[1] = new String("Second");

    // Put the parameters in a Vector.
    Vector params = new Vector();
    params.addElement( strArr );

    Response res = makeCall( call, params );

    // Continue only if response is not null.
    if (res != null) {
      try {
	      String[] respArr = res.getStringArray();
	
	      //System.out.println("Received array of size: " + respArr.length);
	
	      // Display the result of the call.
	      for (int i = 0; i < respArr.length; i++) {
	        form.append( respArr[i] + "\n" );
	      }
      }
      catch (Exception e) {
	      // Display the error.
	      form.append( e.getMessage() + "\n");
      }
    }
  }


  private void testIntArray()
  {
    // Set cache timeout to 1 minute.
    Call call = service.createCall("testIntArray", 1);

    Integer[] intArr = new Integer[ 2 ];
    intArr[0] = new Integer(52);
    intArr[1] = new Integer(23);

    // Put the parameters in a Vector.
    Vector params = new Vector();
    params.addElement( intArr );

    Response res = makeCall( call, params );

    // Continue only if response is not null.
    if (res != null) {
      try {
	      int[] respArr = res.getIntArray();
	
	      // Display the result of the call.
	      for (int i = 0; i < respArr.length; i++) {
	        form.append( String.valueOf(respArr[i]) + "\n" );
	      }
      }
      catch (Exception e) {
	      // Display the error.
	      form.append( e.getMessage() + "\n");
      }
    }
  }
  

  private void testBoolean()
  {
    // Set cache timeout to 1 minute.
    Call call = service.createCall("testBoolean", 1);

    // Put the parameters in a Vector.
    Vector params = new Vector();
    params.addElement( new Boolean(true) );
    
    Response res = makeCall( call, params );

    // Continue only if response is not null.
    if (res != null) {
      try {
	      boolean boolRes = res.getBoolean();
	
	      // Display the result of the call.
	      form.append( String.valueOf(boolRes) + "\n" );
      }
      catch (Exception e) {
	      // Display the error.
	      form.append( e.getMessage() + "\n");
      }
    }
  }


  private void testInteger()
  {
    // Set cache timeout to 1 minute.
    Call call = service.createCall("testInteger", 1);

    // Put the parameters in a Vector.
    Vector params = new Vector();
    params.addElement( new Integer(2002) );

    Response res = makeCall( call, params );

    // Continue only if response is not null.
    if (res != null) {
      try {
	      int intRes = res.getInt();

	      // Display the result of the call.
	      form.append( String.valueOf(intRes) + "\n" );
      }
      catch (Exception e) {
	      // Display the error.
	      form.append( e.getMessage() + "\n");
      }
    }
  }


  private void testDate()
  {
    // Set cache timeout to 1 minute.
    Call call = service.createCall("testDate", 1);

    Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("GMT"));
    Date nowDate = new Date();
    cal.setTime(nowDate);
    form.append("Now = " + cal.toString() + "\n" );

    // Put the parameters in a Vector.
    Vector params = new Vector();
    params.addElement( new Date() );

    Response res = makeCall( call, params );

    // Continue only if response is not null.
    if (res != null) {
      try {
	      Date dateRes = res.getDate();
        cal.setTime(dateRes);

	      // Display the result of the call.
	      form.append("Now + 24 hours = " + cal.toString() + "\n" );
      }
      catch (Exception e) {
	      // Display the error.
	      form.append( e.getMessage() + "\n");
      }
    }
  }


  // Invoke a call.
  private Response makeCall( Call call, Vector params )
  {
    int retCode;
    String msg = null;
    
    Response response;

    if (call == null) {
      msg = "Call object is null!";
    }
    else {
      try {
	      //System.out.println("About to make call...");

	      // Make the remote method invokation.
	      // Response is returned.
	      response = call.invoke(params, false);
	
	      //System.out.println("Call made!");
	
	      if (response == null) {
	        //System.out.println("Response object is null!");
	        msg = "Response object is null.";
	      }
	      else {
	        // Check if the response is valid (0 = OK).
	        retCode = response.getReturnCode();
	  
	        //System.out.println("Return code is: " + retCode);
	  
	        if (retCode == 0) {
	          // Check if the returned object is null.
	          if (response.getObject() == null) {
	            msg = "Null or void return.";
	          }
	          else {
	            return response;
	          }
	        }
	        else {  // return code not 0
	          msg = "Call unsuccessful: " + response.getErrorMsg();
	        }
	      }
      }
      catch (ServiceException e) {
	      msg = new String("Error with code: " + e.getErrorCode() + ", message: " + e.getMessage());
      }
    }

    // Display the result of the call.
    form.append( msg + "\n");

    return null;
  }


  // Clear ALL entries from the response cache.
  void clearCache()
  {
    try {
      ServiceManager sm = ServiceManager.getInstance();
      sm.clearCache();
      form.append( "Cache cleared.\n" );
    }
    catch (ServiceException e) {
      //System.out.println("Error clearing cache: " + e.getErrorCode() + " " + e.getMessage());
      form.append("Error with code: " + e.getErrorCode() + ", clearing cache, message: " + e.getMessage() + "\n");
    }
  }

  // Clear the screen.
  void clearScreen()
  {
    for (int i = (form.size() - 1); i >= 0; i--) {
      form.delete(i);
    }
  }


    class SimpleForm extends Form
    {
	    SimpleForm() {
	      super( "Sample3" );

  	    addCommand(exitCommand);
	      addCommand(vectorCommand);
	      addCommand(hashCommand);
	      addCommand(clearCCommand);
  	    addCommand(clearSCommand);
	      addCommand(strArrCommand);
	      addCommand(intArrCommand);
	      addCommand(boolCommand);
  	    addCommand(intCommand);
        addCommand(dateCommand);

	      setCommandListener(Sample3.this);
	    }
    }
}
