import objectdraw.*;

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

/**
 * Create an array of basketballs and bounce them,
 * but only create balls when you click.
 */
public class BBallArray extends WindowController implements ActionListener {

  private int MAX_BALLS = 10;
  private int BALL_X = 20;
  private int BALL_Y = 200;
  private int BALL_STEP = 30;
  private int BALL_SIZE = 20;

  private BBall[] balls;
  private int ballCount;  // how many balls we've already created.

  public void begin() {
    JButton bounce = new JButton("Bounce");
    bounce.addActionListener(this);
    getContentPane().add(bounce, BorderLayout.SOUTH);
    this.validate();

    balls = new BBall[MAX_BALLS];
    ballCount = 0;
  }

  /*
   * If there is space left in the array, add a new ball. 
   */
  public void onMouseClick(Location pt) {
    if (ballCount < MAX_BALLS) {
      balls[ballCount] = 
      new BBall(BALL_X + BALL_STEP * ballCount, BALL_Y, BALL_SIZE, canvas);
      ballCount++;                                              
    }
  }

  /*
   * Pick a ball and bounce it.  Note that we must create a new generator
   * each time...
   */
  public void actionPerformed(ActionEvent e) {
    if (ballCount > 0) {
      RandomIntGenerator ballPicker = new RandomIntGenerator(0, ballCount - 1);
      new Bouncer(balls[ballPicker.nextValue()]);
    }
  }

}
