import java.awt.*;
import java.awt.image.*;
import java.util.*;


/**
 * A Fish that "swims" in an interesting way.
 *
 * @author  Prof. David Bernstein, James Madison University
 * @version 1.0
 */
public class Fish
{
    protected BufferedImage[]     images;
    protected int                 initialSpeed, maxX, maxY, speed, x, y;
    protected int                 state, stateChange;
    protected int                 ticks, ticksInState;
    
    

    private static final int     INITIAL_LOCATION = -320;    
    private static final Random  rng = new Random();

    /**
     * Explicit Value Constructor
     *
     * @param threeImages  The three Image objects for this Fish
     * @param width        The width of the fishtank
     * @param height       The height of the fishtank
     * @param speed        The normal speed
     */
    public Fish(BufferedImage threeImages, int width, int height, int speed)
    {
       int     imageHeight, imageWidth;
        
       if (threeImages != null)
       {
          imageHeight = threeImages.getHeight(null);
          imageWidth  = threeImages.getWidth(null)/3;
          
          images = new BufferedImage[3];
          for (int i=0; i<3; i++)
          {
             images[i] = threeImages.getSubimage(i*imageWidth,0,
                                                 imageWidth,imageHeight);
          }
       }
       
       maxX = width;
       maxY = height;       

       x    = rng.nextInt(maxX);
       y    = rng.nextInt(maxY);

       this.speed        = speed;       
       this.state        = 0;       
       this.stateChange  = 1;       
       this.ticksInState = 20 - 2*speed;       
    }


    /**
     * Paint this Fish
     *
     * @param g   The rendering engine to use
     */
    public void paint(Graphics g)
    {
       ticks += 1;
       if (ticks > ticksInState)
       {
          ticks = 0;
          state += stateChange;
          if      (state == 2) stateChange = -1;
          else if (state == 0) stateChange =  1;
       }

       x += speed;
       
       if (x > maxX)
       {
          x     = INITIAL_LOCATION;
          y     = rng.nextInt(maxY);
       }

       if (images[state] != null) g.drawImage(images[state], x, y, null);
    }
}
