 import javax.microedition.lcdui.*;
 import javax.microedition.midlet.*;
 import javax.microedition.io.*;
 import java.io.*;

 public class NetobjDemo extends MIDlet implements CommandListener {

 	private Form mMainForm;
 	private TextField idField;
	private TextField msgField;
	private Command exitCommand;
	private Command submitCommand;
	private ConnectionThread connThread = new ConnectionThread();

 	public NetobjDemo() {

		connThread.start();

 		mMainForm = new Form("Networked Objects");

 		mMainForm.append(new StringItem(null, "This is a demo program to communicate with the Networked Objects website."));

		// ID field
 		idField = new TextField("NetID:", "", 10, TextField.ANY);
 		mMainForm.append(idField);

		// Message Field
 		msgField = new TextField("Message:", "", 20, TextField.ANY);
 		mMainForm.append(msgField);

		// add the submit command
		submitCommand = new Command("Submit", Command.SCREEN, 0);
		mMainForm.addCommand(submitCommand);

 		// add the exit command
 		exitCommand = new Command("Exit", Command.EXIT, 0);
 		mMainForm.addCommand(exitCommand);
 		mMainForm.setCommandListener(this);
 	}

 	public void startApp() {

 		Display.getDisplay(this).setCurrent(mMainForm);
 	}

 	public void pauseApp() {

 	}

 	public void destroyApp(boolean unconditional) {

 	}

 	public void commandAction(Command c, Displayable s) {
		if (c == exitCommand) {
			destroyApp(false);
	 		notifyDestroyed();
		} else if (c == submitCommand) {

			// get our message
			String baseURL = "http://www.digilutionary.com/classes/netobj/write.py";
			String user = "user=" + idField.getString();
			String msgText = msgField.getString();
			msgText = replace(msgText, " ", "%20");

			try {
				System.out.println("base: " + baseURL);
				System.out.println("data: " + user + "&msg=" + msgText);
				connThread.post(baseURL, user + "&msg=" + msgText);

				Alert alert = new Alert("Alert!");
				alert.setType(AlertType.INFO);
				alert.setTimeout(3000);
				alert.setString("Sending data now!");
				Display.getDisplay(this).setCurrent(alert);
				System.out.println("sending...");
				while (connThread.sending) {

				}
				Display.getDisplay(this).setCurrent(mMainForm);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
 	}

	String replace(String s, String f, String r) {
		 if (s == null)  return s;
	   if (f == null)  return s;
	   if (r == null)  r = "";

	   int index01 = s.indexOf( f );
	   while (index01 != -1)
	   {
		  s = s.substring(0,index01) + r + s.substring(index01+f.length());
		  index01 += r.length();
		  index01 = s.indexOf( f, index01 );
	   }
	   return s;
	}


}