package com.Series40Book.midp.view;

import com.Series40Book.midp.controller.*;
import javax.microedition.lcdui.*;

/**
 * the ShowQuestionUI using the high level LCDUI classes
 */
public class ShowQuestionUI extends Form
                implements CommandListener {

  private Command restartCommand;
  private Command googleCommand;
  private Command inboxCommand;
  private Command nextCommand;
  private StringItem question;
  private ChoiceGroup choices;
  private ImageItem image;

  public ShowQuestionUI () {
    super("Show Question");

    restartCommand =
        new Command("Restart", Command.SCREEN, 2);
    googleCommand =
        new Command ("Google", Command.SCREEN, 1);
    nextCommand = UIController.nextCommand;
    addCommand(nextCommand);
    addCommand(restartCommand);
    addCommand(googleCommand);

    //#if WMA
    {
      inboxCommand =
          new Command("Inbox", Command.SCREEN, 1);
      addCommand(inboxCommand);
    }
    //#endif

    setCommandListener(this);

    question = new StringItem("", "");
    choices = new ChoiceGroup("", Choice.EXCLUSIVE);
    image = new ImageItem("", null,
        ImageItem.LAYOUT_CENTER, "image");

    append (question);
    append (image);
    append (choices);
  }

  // Construct the UI
  public void setStatus (String q, String [] c,
                         byte [] img, byte [] sound) {

    question.setText(q);
    image.setImage(Image.createImage(img, 0, img.length));
    choices =
        new ChoiceGroup("", Choice.POPUP, c, null);
    // The third item is the choice group
    set (2, choices);

    /* This does not work reliably
    int n = choices.size ();
    for (int i = 0; i < n; i++) {
      choices.delete(i);
    }
    for (int i = 0; i < c.length; i++) {
      choices.append (c[i], null);
    }
    choices.setSelectedIndex(0, true);
    */

    SoundPlayer sp = new SoundPlayerImpl ();
    sp.playSound(sound);
  }

  public void commandAction (Command c, Displayable s) {
    try {
      if (c == restartCommand) {
        UIController.restartQuestion();
      } else if (c == googleCommand) {
        UIController.showGoogleQuery(this);
      } else if (c == inboxCommand) {
        //#if WMA
        {
          UIController.firstMessage(this);
        }
        //#endif
      } else if (c == nextCommand) {
        UIController.storeAnswer(
            choices.getSelectedIndex());
      }
    } catch (Exception e) {
      e.printStackTrace();
      UIController.showAlert("Error",
                             e.getMessage(), this);
    }
  }

}
