package com.Series40Book.GaugeWaitViewer;

import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;
import com.Series40Book.Util.*;

public class PhotoViewer extends MIDlet {

  public static Display display;
  private static PhotoViewer controller;

  public static String url;

  public PhotoViewer () {
    display = Display.getDisplay(this);
    controller = this;
  }

  protected void startApp () {

    url = getAppProperty ("PhotoServerURL");

    Form view = new View ("Photo Viewer");
    view.append ("Select Fetch to start");
    display.setCurrent (view);
  }

  protected void pauseApp () {
    // Do nothing
  }

  protected void destroyApp (boolean unconditional) {
    // Do nothing
  }

  public static void exit () {
    controller.destroyApp (true);
    controller.notifyDestroyed ();
  }

  public static void getPhoto () {
    Form screen = new GaugeWait ();
    display.setCurrent (screen);

    Thread t = new Thread (new FetchWorker(url));
    t.start ();
  }

  public static void showPhoto(String title,
                String description, Image img,
                boolean isSuccessful) {

    Form view = new View(title);
    if (isSuccessful) {
      view.append(new ImageItem(description, img,
          ImageItem.LAYOUT_CENTER, ""));
    } else {
      view.append(new StringItem("Status",
          "The network is NOT available"));
    }

    display.setCurrent(view);
  }

}

class View extends Form
        implements CommandListener {

  private Command fetch, exit;

  public View (String title) {
    super (title);

    fetch = new Command ("Fetch", Command.SCREEN, 1);
    exit = new Command ("Exit", Command.EXIT, 1);
    addCommand (fetch);
    addCommand (exit);
    setCommandListener (this);
  }

  public void commandAction (Command c, Displayable d) {
    if (c == exit) {
      PhotoViewer.exit ();
    } else if (c == fetch) {
      PhotoViewer.getPhoto ();
    }
  }
}

class FetchWorker extends Fetch implements Runnable {

  public FetchWorker (String url) {
    super (url);
  }

  public void run () {
    getPhoto ();

    PhotoViewer.showPhoto(title, description,
                          img, isSuccessful);
  }
}

class GaugeWait extends Form
    implements CommandListener {

  private Command exit;

  public GaugeWait() {
    super("Please wait ...");

    Gauge g = new Gauge ("In progress", false,
          Gauge.INDEFINITE, Gauge.CONTINUOUS_RUNNING);
    append (g);

    exit = new Command("Exit", Command.EXIT, 1);
    addCommand(exit);
    setCommandListener(this);
  }

  public void commandAction(Command c, Displayable d) {
    if (c == exit) {
      PhotoViewer.exit();
    }
  }
}