import java.applet.*;
import java.awt.*;
import java.awt.event.*;
/**
 * This class defines the applet, and sets up the Model and View objects.
 * If we had user controls (such as Start and Stop buttons, or a speed
 * control), this is where they would be defined and handled.<p>
 * This example is more complex than it needs to be, because it enforces
 * a strict separation between the model (the part that does the actual
 * computation), the display, and the controls in the user interface (of
 * which there are none). This is called the MVC (Model-View-Controller)
 * pattern, and while it may be overkill for this example, MVC provides an
 * excellent basis for more complex animations.
 */
public class Controller extends Applet {
  // Create the model (the ball) and the view (the animation)
  Thread animation;
  Model model = new Model();
  View view = new View();
  
  /**
   * Lays out the applet components, starts a new thread for the
   * view to do its animation, and gives the model, view, and
   * controller access to one another.
   */
  public void init() {
  
    // Lay out components
    setLayout(new BorderLayout());
    this.add(BorderLayout.CENTER, view);
    // Give the view its own thread in which to do the animation
    animation = new Thread(view);
    animation.start();
    
    // Get applet parameters and put them where they belong
    view.delay = Integer.valueOf(getParameter("delay")).intValue();
    
    // Tell the view about the model and the controller
    view.model = model;
    view.controller = this;
  }
  
  /**
   * Finds the size of the canvas (this can't be done in init()
   * because the canvas isn't ready yet) and gives the animation
   * permission to run.
   */
  public void start() {
    model.xLimit = view.getSize().width - model.BALL_SIZE;
    model.yLimit = view.getSize().height - model.BALL_SIZE;
    view.alive = true;
    view.okToRun = true;
  }
  
  /**
   * Withdraws permission for the animation to run.
   */
  public void stop() {
    view.okToRun = false;
  }
  
  /**
   * Tells the animation thread to stop running.
   */
  public void destroy() {
    view.alive = false;
  }
}

