// Test sample 4.

package oracle.wireless.me.sample1;

import java.util.Vector;
import java.util.Enumeration;

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

import oracle.wireless.me.core.*;

/**
 * Sample4 calls the bye method in TestWebService2, which is a singleton
 * class.
 */
public class Sample4 extends MIDlet implements CommandListener
{
    private Display display;
    private Form form;
    private Command exitCommand;
    private Command goCommand;
    private Command clearCCommand;
    private Command clearSCommand;

    private ServiceFactory serviceFactory;
    private Service service;

    public Sample4()
    {
    }

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

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

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

    public void commandAction(Command c, Displayable d)
    {
	    if (c == exitCommand) {
	      exitMIDlet();
	    }
	    else if (c == goCommand) {
	      callService();
	    }
	    else if (c == clearCCommand) {
	      clearCache();
	    }
	    else if (c == clearSCommand) {
	      clearScreen();
	    }
    }

    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", "TestWebService2");

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

      exitCommand = new Command("Exit", Command.EXIT, 1);
      goCommand = new Command("bye", Command.SCREEN, 1);
      clearCCommand = new Command("Clear Cache", Command.SCREEN, 2);
      clearSCommand = new Command("Clear Screen", Command.SCREEN, 2);

      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();
  }


  // Make a normal remote procedure call to
  // a web service that is created with a getInstance method.
  private void callService()
  {
    // Set cache timeout to 1 minute.
    Call call = service.createCall("bye", 1);

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

    makeCall( call, params );
  }


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

    if (call == null) {
      retVal = "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!");
	        retVal = "Response object is null.\n";
	      }
	      else {
	        // Check if the response is valid (0 = OK).
	        retCode = response.getReturnCode();
	  
	        //System.out.println("Return code is: " + retCode);
	  
	        if (retCode == 0) {
	          // All of the examples in this midlet return a string
	          // or have a void return type.
	          // Check if the string is null.
	          if (response.getString() == null) {
	            retVal = "Null or void return.\n";
	          }
	          else {
	            retVal = response.getString() + "\n";
	          }
	        }
	        else {  // return code not 0
	          retVal = "Call unsuccessful: " + response.getErrorMsg() + "\n";
	        }
	      }
      }
      catch (ServiceException e) {
	      retVal = new String("Error with code: " + e.getErrorCode() + ", message: " + e.getMessage() + "\n");
      }
    }

    // Display the result of the call.
    form.append( retVal );
  }


  // 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( "Sample4" );

	      addCommand(exitCommand);
	      addCommand(goCommand);
	      addCommand(clearCCommand);
	      addCommand(clearSCommand);

	      setCommandListener(Sample4.this);
	    }
    }
}
