import java.awt.*;
import javax.swing.*;

/*
  this is the View component
  the view component is responsible for displaying the output in a graphical window (a JPanel)
  this can be as complicated as the teacher wants.  The student interface is only through the
  updateView method, passing the data structure to be displayed.
*/

class HailstoneView extends JPanel
{
    private int[] mySteps;

    // entry point from model, requests grid be redisplayed
    public void updateView( int[] steps )
    {
        mySteps = steps;
        repaint();
    }

	// the model calls updateView, which makes a request to repaint, and the OS
	// makes a call to paintComponent to do the actual drawing.
    public void paintComponent(Graphics g)
    {
        super.paintComponent(g);
		
		// figure scale factors for useful display
		int yMax=0, xCount = 0;
		for ( int i = 0; i < Hailstone.MAXSTEPS; i++ )
		{
			if (mySteps[i] != 0) 
			{
				xCount += 1;
				if (mySteps[i] > yMax)
					yMax = mySteps[i];
			}
		}
		double xStep = (double)(getWidth()) / xCount;
		double yScale = (0.9)*((double)(getHeight()) / yMax);
		
		// line segment endpoints and starting point
		int xNext, xLast = 0;
		int yNext, yLast = (int)(mySteps[0] * yScale);

        for ( int i = 1; i < Hailstone.MAXSTEPS; i++ )
        {
			if (mySteps[i] != 0)
			{
				xNext = (int)(i * xStep);
				yNext = (int)(mySteps[i] * yScale);
				// mirror upside down for humans
				g.setColor( new Color(200, 200, 255) );
				g.drawLine( xLast, getHeight()-yLast, xNext, getHeight()-yNext );
				g.setColor( Color.black );
				g.fillOval( xNext-1, getHeight()-yNext-1, 3, 3 );
				xLast = xNext;
				yLast = yNext;
			}
        }
    }
}
