package com.ociweb.j2me.midp.wireless;

import java.io.*;
import java.util.*;

import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;

public class WirelessMIDlet extends MIDlet implements CommandListener {

    /** location of the servlet we will connect to */
    private String servletURL = "http://www.ociweb.com/J2ME/echo";
    //private String servletURL = "http://balbes:8080/J2ME/echo";

    private Display display;
    private Command exitCommand = new Command("Exit", Command.EXIT, 1);
    private Command getCommand = new Command("GET", Command.SCREEN, 2);
    private Command postCommand = new Command("POST", Command.SCREEN, 2);
    private Command okCommand = new Command("OK", Command.OK, 2);
    private Command backCommand = new Command("BACK", Command.BACK, 2);
    private StringItem stringItem = new StringItem("", "GET/POST example");

    /** First screen of the application */
    private Form splashScreen = new Form("HTTP Demo", new Item[]{stringItem});

    /** Screen containing the URL to connect to */
    private TextBox urlEntryScreen = new TextBox("Servlet URL", servletURL, 255, TextField.URL);

    private TextField name1Field = new TextField("Name 1:", "", 10, TextField.ANY);
    private TextField value1Field = new TextField("Value 1:", "", 10, TextField.ANY);
    private TextField name2Field = new TextField("Name 2:", "", 10, TextField.ANY);
    private TextField value2Field = new TextField("Value 2:", "", 10, TextField.ANY);

    /** Screen containing the parameters to be passed to the server */
    private Form parameterInputScreen =
        new Form("Enter Parameters:",
                 new Item[]{name1Field, value1Field, name2Field, value2Field});

    private Alert resultsScreen = new Alert("Results", "No results", null, AlertType.INFO);
    private Alert errorScreen = new Alert("Error", "An unknown error occurred", null, AlertType.ERROR);

    public WirelessMIDlet() {
        // create/configure the splash screen
        splashScreen.addCommand(exitCommand);
        splashScreen.addCommand(okCommand);
        splashScreen.setCommandListener(this);

        // create/configure the URL Display screen
        urlEntryScreen.addCommand(exitCommand);
        urlEntryScreen.addCommand(okCommand);
        urlEntryScreen.setCommandListener(this);

        // create/configure the parameter input screen
        parameterInputScreen.addCommand(backCommand);
        parameterInputScreen.addCommand(getCommand);
        parameterInputScreen.addCommand(postCommand);
        parameterInputScreen.setCommandListener(this);

        // create/configure the results screen
        resultsScreen.setTimeout(Alert.FOREVER);
    }

    protected void pauseApp() { }
    protected void destroyApp(boolean parm1) { }

    protected void startApp() {
        display = Display.getDisplay(this);
        showSplashScreen();

    }

    private void showSplashScreen() {
        display.setCurrent(splashScreen);
    }

    private void showURLEntryScreen() {
        display.setCurrent(urlEntryScreen);
    }

    private void showParameterInputScreen() {
        display.setCurrent(parameterInputScreen);
    }

    /** Create a Hashtable with the desired request parameters. */
    private Hashtable getRequestParameters() {
        Hashtable params = new Hashtable(2);
        params.put(name1Field.getString(), value1Field.getString());
        params.put(name2Field.getString(), value2Field.getString());

        return params;
    }

    /** Use HTTP GET to request the information from the servlet */
    private String get() throws IOException {
        // Create the hashtable of parameters
        Hashtable params = getRequestParameters();
        return HTTPHelper.get(servletURL, params);
    }

    /** Use HTTP POST to request the information from the servlet */
    private String post() throws IOException {
        // Create the hashtable of parameters
        Hashtable params = getRequestParameters();
        return HTTPHelper.post(servletURL, params);
    }

    private void exit() {
        destroyApp(false);
        notifyDestroyed();
    }

    public void commandAction(Command command, Displayable displayable) {
        if (displayable == splashScreen) {
            if (command == exitCommand) {
                exit();
            } else if (command == okCommand) {
                showURLEntryScreen();
            }
        } else if (displayable == urlEntryScreen) {
            if (command == exitCommand) {
                exit();
            } else if (command == okCommand) {
                servletURL = urlEntryScreen.getString();
                showParameterInputScreen();
            }
        } else if (displayable == parameterInputScreen) {
            if (command == backCommand) {
                showURLEntryScreen();
            } else {
                try {
                    String result;
                    if (command == getCommand) {
                        result = get();
                    } else if (command == postCommand) {
                        result = post();
                    } else {
                        throw new IllegalStateException("Command is not get or post");
                    }
                    resultsScreen.setString(result);
                    display.setCurrent(resultsScreen, parameterInputScreen);
                } catch (IOException e) {
                    errorScreen.setString("Could not get the requested page.");
                    display.setCurrent(errorScreen);
                }
            }
        }
    }
}