import java.util.Random;

public class PondStocker
{
  private Environment theEnv;
  private double minDensity;   // 0.0 <= minDensity < 1.0

  public PondStocker(Environment env, double min)
  { theEnv = env;
    minDensity = min;
  }

  // postcondition: returns the minimum number of fish that need to be
  //                added to make the population density greater than
  //                minDensity
  private int numUnder()
  { int numCells = theEnv.numRows() * theEnv.numCols();
    int minNum = (int)(minDensity * numCells) + 1;

    int result = minNum - theEnv.numObjects();
    if(result > 0)
      return result;
    else
      return 0;
  }

  // precondition:  0 <= numToAdd <= number of empty locations in theEnv
  // postcondition: the number of fish in theEnv has been increased
  //                by numToAdd. The fish added are placed at
  //                random empty locations in theEnv
  private void addFish(int numToAdd)
  {
    while(numToAdd > 0)
    {
      Location loc = randomLocation();
      while(!theEnv.isEmpty(loc))
        loc = randomLocation();

      new Fish(theEnv, loc);
      numToAdd--;
    }
  }
// alternate 1
/*
  {
    while(numToAdd > 0)
    {
      Location loc = randomLocation();
      if(theEnv.isEmpty(loc))
      {
        new Fish(theEnv, loc);
        numToAdd--;
      }
    }
  }
*/
// alternate 2
/*
{
    for(int k = 0; k < numToAdd; k++)
    {
      Location loc = randomLocation();
      while(!theEnv.isEmpty(loc))
        loc = randomLocation();

      new Fish(theEnv, loc);
    }
  }
*/
  // postcondition: minDensity < density of environment
  public void adjustPopulation()
  { addFish(numUnder());
  }

  // postcondition: returns a random location within the bounds of theEnv
  private Location randomLocation()
  { Random rand = RandNumGenerator.getInstance();

    int row = rand.nextInt(theEnv.numRows());
    int col = rand.nextInt(theEnv.numCols());
    return new Location(row, col);
  }

}
