/*
 * A simple MIDlet that uses regular expressions.
 * Type in a pattern, some text to match against, then
 * select the match button. It works!
 */

package regex;

import javax.microedition.MIDlet.*;
import javax.microedition.lcdui.*;
import com.stevenrbrandt.ubiq2.v15.pattwo.*;

public class RegexMIDlet extends MIDlet implements CommandListener {

    private Command exitCommand, matchCommand; // The exit command
    private Display display;     // The display for this MIDlet
    private TextField pattern, text;
    private StringItem match;

    public RegexMIDlet() {
        display = Display.getDisplay(this);
        exitCommand = new Command("Exit", Command.EXIT, 0);
        matchCommand = new Command("Match",Command.OK,1);
        pattern = new TextField("Pattern", "", 10, 0);
        text = new TextField("Text", "", 10, 0);
        match = new StringItem("Result", "");
    }

    public void startApp() {
        Form f = new Form("Regex MIDlet");
        f.append(pattern);
        f.append(text);
        f.append(match);
        f.addCommand(matchCommand);
        f.addCommand(exitCommand);
        f.setCommandListener(this);
        display.setCurrent(f);
    }

    public void pauseApp() {
    }

    public void destroyApp(boolean unconditional) {
    }

    public void commandAction(Command c, Displayable s) {
        if (c == exitCommand) {
            destroyApp(false);
            notifyDestroyed();
        }
        if (c == matchCommand) {
            Pattern p = Pattern.compile(pattern.getString());
            Matcher m = p.matcher(text.getString());
            if(m.find())
                match.setText(m.group());
            else
                match.setText("**NO MATCH**");
        }
    }
}
