package candy;

import java.util.Random;

/**
 * A machine that dispenses a few chicklets at a time.
 *
 * @author Samuel A. Rebelsky
 * @version 1.1 of September 2006
 */
public class ChickletMachine
	implements CandyMachine
{

// +--------+------------------------------------------------------------
// | Fields |
// +--------+

	/**
	 * The number of chicklets remaining in the machine.
	 */
	int chicklets;

	/**
	 * A random number generator, used to select how many
	 * chicklets to distribute.
	 */
	Random rng;


// +--------------+------------------------------------------------------
// | Constructors |
// +--------------+

	/**
	 * Build a new Chicklet machine with the default number of
	 * chicklets.
	 */
	public ChickletMachine()
	{
		this.rng = new Random();
		this.chicklets = 60 + this.rng.nextInt(21);
	} // ChickletMachine()

// +----------+----------------------------------------------------------
// | Mutators |
// +----------+

	/**
	 * Get a piece of candy.
	 *
	 * @exception CandyMachineException
	 *   If unable to return a piece of candy (e.g., if empty).
	 */
	public String get()
		throws CandyMachineException
	{
		if (this.chicklets <= 0)
			throw new EmptyMachineException();
		else {
			// Dispense between 5 and 9 chicklets.
			int dispense = 5 + this.rng.nextInt(5);
			if (dispense > this.chicklets)
				dispense = this.chicklets;
			this.chicklets -= dispense;
			return dispense + " chicklets";
		} // else
	} // get()

// +-----------+---------------------------------------------------------
// | Observers |
// +-----------+

	/**
	 * Determine if the machine is empty.
	 */
	public boolean isEmpty()
	{
		return (this.chicklets <= 0);
	} // isEmtpy()

} // class ChickletMachine

