/**
 * PushDemoMIDlet.java
 *
 * Created on March 12, 2002, 6:02 PM
 */

package oracle.wireless.me.sample1;

import oracle.wireless.me.core.*;
import java.util.Hashtable;
import java.util.Vector;
import java.util.Timer;
import java.util.TimerTask;
import java.lang.Integer;

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

// Generated client stub for PushServer
import PushServerJ2MEStub;

/**
 * An example MIDlet utilizing oracle.wireless.me.messaging.Push
 * API to send message out through Oracle Hosted Messaging Server.
 * Register the PushServer web service at the J2ME Proxy Server using
 * the PushLite.wsdl document.
 *
 * For email messages, To field is an email address.
 * For voice, fax, or sms message, To field is a complete phone number
 * (for example: 1-800-555-1212 ).
 *
 * @author  jianwu
 * @version 1.0
 */
public class PushDemoMIDlet extends MIDlet implements CommandListener, ItemStateListener
{
    private Display display;    // The display for this MIDlet

    // a menu with items
    List menu = null; // main menu

    // list of choices
    List choose = null;

    // textbox
    TextBox input = null;

    // form
    Form form = null; // Host Form
    Form subjectForm = null; // Subject Form

    // text fields
    TextField tTransport    = null;
    TextField tFrom    = null;
    TextField tTo    = null;

    TextField tSubject = null;
    TextField tMsg = null;


    String currentMenu = null;
    String newTask     = null;

    String transportIndex = null;
    String transport = null;
    String from = null;
    String recipients = null;
    String subject  = null;
    String message = null;
    
    private PushServerJ2MEStub pushClient;
   
    // commands
    static final Command backCommand = new Command(     "Back", Command.BACK, 0 );
    static final Command exitCommand = new Command(     "Exit", Command.STOP, 2 );
    static final Command menuCommand = new Command(     "Send", Command.SCREEN, 1 );
    static final Command nextCommand = new Command(     "Next", Command.SCREEN, 1 );

    static final String TRANSPORT_TYPES[]={"","Email", "Voice", "Fax", "SMS"};

    public PushDemoMIDlet()
    {
    }

    /******************
     * MIDlet Methods *
     ******************/
    public void startApp()
    {
      if (display == null) {
        display = Display.getDisplay( this );
        pushClient = new PushServerJ2MEStub();
      }
      mainMenu();
    }


    /**
     * On pause, close the record store used for caching by calling
     * ServiceManager.close().
     */
    public void pauseApp()
    {
      try {
        ServiceManager.getInstance().close();
      }
      catch (Exception e) {
      }
    }

    /**
     * Destroy must cleanup everything not handled by the garbage collector.
     * ALWAYS call ServiceManager.close() to close the record store used
     * for caching.
     */
    public void destroyApp(boolean unconditional)
    {
      try {
        ServiceManager.getInstance().close();
      }
      catch (Exception e) {
      }

      notifyDestroyed();
    }

    /**
     * Respond to commands, including exit
     * On the exit command, cleanup and notify that the MIDlet has been destroyed.
     */
    public void commandAction(Command c, Displayable s)
    {
        String label = c.getLabel();

        if ( label.equals( "Exit" ) )
        {
            destroyApp( true );
        }
        else if ( label.equals( "Back" ) )
        {
            if ( currentMenu.equals( "list" ) ||
                 currentMenu.equals( "form" ) || 
                 currentMenu.equals( "bufferedReqs" ) )
            {
                // go back to menu
                mainMenu();
            }
            else if ( currentMenu.equals( "subjectform" ) )
            {
                this.inputFrom();
            }
        }
        else if ( label.equals( "Next" ) )
        {
            if ( currentMenu.equals( "form" ) )
            {
                this.inputSubject();
            }
        }
        else if ( label.equals( "Send" ) )
        {
            sendMessage();
        }
        else
        {
            // Handle the list command based on different menu name
            if ( currentMenu.equals( "Main" ) )
            {
                List down = (List)display.getCurrent();
                switch( down.getSelectedIndex() ) 
                {
                    case 0: 
                        inputFrom();
                        break;
                    case 1:
                        break;
                }
            }
        }
    }

    /**
     * ItemStateListener method
     */
    public void itemStateChanged( javax.microedition.lcdui.Item item )
    {
        if ( item instanceof TextField )
        {
            if ( currentMenu.equals( "form" ) )
            {
                this.from = tFrom.getString();
                this.recipients = tTo.getString();
                this.transportIndex = tTransport.getString();
                
                int index = Integer.parseInt(transportIndex);
                if(index <1)
                {
                    index = 1;
                    transportIndex = new String(new Integer(index).toString());
                }
                
                if( index >= TRANSPORT_TYPES.length)
                {
                    index = TRANSPORT_TYPES.length - 1;
                    transportIndex = new String(new Integer(index).toString());
                }                
                    
                this.transport = TRANSPORT_TYPES[index];
            }
            else if ( currentMenu.equals( "subjectform" ) )
            {
                this.subject = tSubject.getString();
                this.message = tMsg.getString();
            }
        }
    }

    /**************
     * UI Methods *
     **************/
    void mainMenu()
    {
      if ( menu == null )
      {
         
          menu = new List( "Push Demo List", Choice.IMPLICIT );
          menu.append( "Send Message", null );

          menu.addCommand( exitCommand );
          menu.setCommandListener( this );
      }

      display.setCurrent( menu );
      currentMenu = "Main";

      input = null;
    }

   public void inputFrom()
   {
      if ( form == null)
      {
          form = new Form( "From" );

          String trans = "";
          for(int i=1;i<TRANSPORT_TYPES.length;i++)
          {
              trans += Integer.toString(i) + "-" + TRANSPORT_TYPES[i] + ",";
          }

          trans += "\nTransport type:";

          tTransport = new TextField(trans, transportIndex, 1, TextField.NUMERIC);
          form.append(tTransport);
          
          tFrom = new TextField( "From", from, 50, TextField.ANY );
          form.append( tFrom );
          
          tTo = new TextField("To:", recipients, 80, TextField.ANY);
          form.append(tTo);

          form.addCommand( backCommand );
          form.addCommand( nextCommand );

          form.setCommandListener( this );
          form.setItemStateListener( this );
      }
      else
      {
          if(from != null)
              tFrom.setString(from);
          if(recipients != null)
              tTo.setString(recipients);
          if(transport != null)
              tTransport.setString(transportIndex);
      }

      display.setCurrent( form );
      currentMenu = "form";
   }

    public void inputSubject()
    {
      if ( this.subjectForm == null)
      {
          subjectForm = new Form( "Subject and Msg body" );
          tSubject = new TextField( "Subject", subject, 50, TextField.ANY );
          subjectForm.append( tSubject );

          tMsg = new TextField( "Msg Body", message, 160, TextField.ANY );
          subjectForm.append( tMsg );

          subjectForm.addCommand( backCommand );
          subjectForm.addCommand( menuCommand );

          subjectForm.setCommandListener( this );
          subjectForm.setItemStateListener( this );
      }
      else
      {
          if ( subject != null )
          {
              tSubject.setString( subject );
          }
          if(message != null)
              tMsg.setString(message);
      }

      display.setCurrent( subjectForm );
      currentMenu = "subjectform";
    }

    void sendMessage()
    {
        String result = null;
        if ( this.transport == null || this.transport.trim().length() == 0 
            || this.recipients == null || this.recipients.trim().length() == 0 )
        {
            Alert errAlert = new Alert( "Send Alert", "Please input recipient address", null, AlertType.ERROR );
            errAlert.setTimeout( Alert.FOREVER );
            display.setCurrent( errAlert, this.form );
            currentMenu = "form";

        }
        else
        {
          try {
            result = callPushService( transport, this.from, recipients, this.subject, this.message );

            if ( result != null)
            {
               Alert stsAlert = new Alert( "Message Sent", "Push Message Sent out. Msg ID(s):" + result, null, AlertType.CONFIRMATION );
               stsAlert.setTimeout( Alert.FOREVER );
               display.setCurrent( stsAlert, this.menu );
               currentMenu = "Main";

               // System.out.println( "Message Sent" );
            }
            else if ( result == null )
            {
               Alert errAlert = new Alert( "Send Message", "Send Message Failed: no message IDs returned", null, AlertType.ERROR );
               errAlert.setTimeout( Alert.FOREVER );
               display.setCurrent( errAlert, this.menu );
               currentMenu = "Main";

              // System.out.println( "Message Failed: no message IDs returned" );
            }
          }
          catch (ServiceException e) {
            Alert errAlert = new Alert( "Send Message", "Send Message Failed: " + e.getMessage(), null, AlertType.ERROR );
            errAlert.setTimeout( Alert.FOREVER );
            display.setCurrent( errAlert, this.menu );
            currentMenu = "Main";

            // System.out.println( "Message Failed: " + e.getMessage() );
          }
        }
    }

    private String callPushService( String transport, String from, String recipients, String subject, String message )
        throws ServiceException
    {
        String msgIDs[] = null;
        String[] sender = {transport+":"+from};
        String[] rec = {transport+":"+recipients};

        // Many Text-To-Speech processors read out individual letters
        // instead of words if all letters are upper case.  Since many phones
        // can only enter upper case letters, set subject and message to
        // lower case when the message is going to voice.
        if (transport.equals("Voice")) {
          subject = subject.toLowerCase();
          message = message.toLowerCase();
        }

        // Third and fourth parameters are username and password
        // to messaging server, if any.
        msgIDs = pushClient.sendText(0, true,"","",sender,null,rec,null,
                                     subject,message,"text/plain");
        //msgIDs = pushClient.sendTextMsg(0, true,"","",sender,rec,
        //                               "Subject: "+subject+" \n"+"Body: "+message);

        if(msgIDs != null)
        {
            StringBuffer sb = new StringBuffer();
            for(int i=0;i<msgIDs.length;i++)
            {
                if(i==0)
                    sb.append(msgIDs[i]);
                else
                {
                    sb.append(",");
                    sb.append(msgIDs[i]);
                }
            }
            return sb.toString();
        }
        else
            return null;
         
    }
    
}
