package com.Series40Book.midp.controller;

import javax.microedition.lcdui.*;

public class WaitScreen extends Canvas
                    implements CommandListener {

  private int maxCount = 10;
  private int count = 0;
  public String message = "";

  private Command stop;
  private Image img;
  private WorkerRunnable worker;

  int width = getWidth ();
  int height = getHeight ();

  public WaitScreen () {
    try {
      img = Image.createImage("/" + "wait.png");
    } catch (Exception e) {
      e.printStackTrace ();
      img = null;
    }
    stop = new Command ("Stop", Command.EXIT, 1);
    addCommand (stop);
    setCommandListener (this);
  }

  public void setWorker (WorkerRunnable w) {
    worker = w;

    // The worker updates the current screen
    worker.setWait(this);
    Thread t = new Thread(worker);
    t.start();
  }

  public void setCount (int value) {
    count = value % maxCount;
    repaint ();
    serviceRepaints ();
  }

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

  public void paint (Graphics g) {
    g.setColor(0xffffff);
    g.fillRect(0,  0, width, height);
    g.setColor(0x000000);

    g.drawImage (img, width / 2, height / 3,
            Graphics.HCENTER | Graphics.VCENTER);

    int buffer = 10; // Pixels at both ends of the bar

    int endX = buffer +
          ((width - (2 * buffer)) * count / maxCount);
    g.setColor(0, 0, 255);
    int startY = height * 2 / 3;
    g.fillRect(buffer, startY,
               endX-buffer, 15);

    g.setFont(Font.getFont(Font.FACE_PROPORTIONAL,
        Font.STYLE_PLAIN, Font.SIZE_SMALL));
    g.drawString (message, width/2, height*2/3 - 10,
             Graphics.BASELINE | Graphics.HCENTER);
    return;
  }
}