import java.awt.*;

/**
 * This class runs in a separate (animation) thread and controls all the
 * painting.
 */
class View extends Canvas implements Runnable {
  Controller controller;
  Model model;
  Dimension size = getSize();
  int delay = 1000;
  int stepNumber = 0;
  boolean alive, okToRun;
  Image offscreenImage = null;
  Graphics offscreenGraphics = null;
  int skullNumber = 0;

  /**
   * Sets up an (almost) infinite loop to do the animation, and every
   * delay milliseconds asks the model to update itself, then draws the
   * result.
   */
  public void run() {
    // "alive" will be true until the Applet is destroyed
    while(alive) {
      // "okToRun" will be true if the Applet is started and not stopped
      if(okToRun) {
        model.makeOneStep();
        repaint(); // Note: uses Graphics for this Canvas, not for the Applet
      }
      // Control the speed of execution
      try { Thread.sleep(delay); }
      catch(InterruptedException e) {}
    }
  }
  
  /**
   * To avoid flicker, this method paints into the Graphics
   * of an offscreen Image.
   */
  public void update(Graphics g) {
      
    // Don't do anything without permission from the controller
    if (!okToRun) return;
    
    // Create the offscreen Graphics
    if (offscreenImage == null) {
      offscreenImage = createImage(getSize().width, getSize().height);
      offscreenGraphics = offscreenImage.getGraphics();
    }
    // Paint into the offscreen Graphics
    background(offscreenGraphics);
    paint(offscreenGraphics);
    
    // Copy the offscreen onto the screen
    g.drawImage(offscreenImage, 0, 0, null);
  }
  
  /**
   * Repaints the canvas based on information that it gets from the model.
   */
  public void paint(Graphics g) {
  
    // Don't do anything without permission from the controller
    if (!okToRun) return;

    // Draw new skull
    skullNumber = (skullNumber + 1) % 24;
    g.drawImage(controller.skull[skullNumber], model.xPosition, model.yPosition, null);

    // Display steps and position in the status line;
    // this is a good place to put debugging information.
    if(++stepNumber % 10 == 0)
      controller.showStatus("Step " + stepNumber + ", x = " + model.xPosition +
                            ", y = " + model.yPosition);
  }
  
  /**
   * Paints a background on the given Graphics.
   */
   void background(Graphics g) {
     g.drawImage(controller.graveyard, 0, 0, null);
   }
}
