package com.Series40Book.BasicUI;

import javax.microedition.lcdui.*;


public class AnimationDemo extends Canvas
             implements CommandListener {

  private Command start, stop;
  private Animator animator;
  private CommandListener comm;
  private Image img;
  private Font font;
  public int currentPosX, currentPosY;
  public int width, height;

  public AnimationDemo (CommandListener c) {
    comm = c;
    width = getWidth ();
    height = getHeight ();
    // position of the text
    currentPosX = width / 2;
    currentPosY = 10;
    // text font
    font = Font.getFont(Font.FACE_SYSTEM,
            Font.STYLE_ITALIC, Font.SIZE_LARGE);
    animator = new Animator (this);

    // setFullScreenMode (true);
    start = new Command ("Start", Command.SCREEN, 2);
    stop = new Command ("Stop", Command.SCREEN, 2);

    addCommand (start);
    addCommand (stop);
    setCommandListener (this);

    try {
      img = Image.createImage("/" + "telescope.png");
    } catch (Exception e) {
      e.printStackTrace ();
      img = null;
    }
  }


  public void commandAction (Command c, Displayable d) {
    if (c == start) {
      Thread t = new Thread (animator);
      t.start ();
    } else if (c == stop) {
      animator.stopped = true;
    }
    comm.commandAction(c, d);
  }

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

    g.setColor(0x000000);
    g.drawImage (img, width / 2, height / 2,
            Graphics.HCENTER | Graphics.VCENTER);
    g.setFont (font);
    g.setColor (255, 0, 0);
    g.drawString ("Telescope", currentPosX, currentPosY,
            Graphics.BASELINE | Graphics.HCENTER);
  }
}

class Animator implements Runnable {

  AnimationDemo demo;
  public boolean stopped;

  public Animator (AnimationDemo demo) {
    this.demo = demo;
    stopped = false;
  }

  public void run () {
    while (!stopped) {
      demo.currentPosY += 5;
      if (demo.currentPosY > demo.height) {
        demo.currentPosY = 0;
      }
      demo.repaint ();
    }
  }
}
