import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import javax.swing.JPanel;

/**
 * The class that represents a view of the model.
 * Here, the model is just a number that goes up and down over time
 * and the view is just a point whose x-value represents time
 * and whose y-value represents the model's number.
 *
 * @author David Mutchler.
 *         Created October 17, 2008.
 */
public class View extends JPanel implements Runnable {
	private static final long SLEEP_MILLISECONDS = 20;
	
	private boolean isPaused;
	
	private Model model;
	private int x;
	private int y;
	
	/**
	 * Constructs and initializes the view, storing its associated model.
	 * 
	 * @param model Model associated with this view.
	 */
	public View(Model model) {
		this.model = model;
		this.isPaused = false;
		this.x = 0;
		
		this.setPreferredSize(new Dimension(300, 300));
		this.setBackground(Color.blue);
	}

	/**
	 * Repeatedly repaints this view.
	 */
	public void run() {
		
		while (true) { // This animation runs forever.
			if (this.isPaused) {
				continue; // Just continue the loop if the animation is paused.
			}

			try { // Sleep so the animation is drawn at a reasonable pace.
				Thread.sleep(View.SLEEP_MILLISECONDS);
			} catch (InterruptedException exception) {
				// Just continue the loop if you cannot sleep.
			}
			
			this.repaint();
		}
	}
	
    /**
     * Draw the current state of the data (animation).
     *
     * @param graphics Graphics object to draw upon
     */
    @Override
	public void paintComponent(Graphics graphics) {
    	super.paintComponent(graphics);
    	
		// Get the data from the model.
		this.y = 150 + (int) (this.model.getData());
		
		// Display the data.
		this.x = (this.x + 1) % 300;	// Wrap the x (time) axis.
		graphics.setColor(Color.red);
		graphics.fillOval(this.x, this.y, 20, 20);
    }
    
    /**
     * Toggle between the is-paused state to the not-paused state.
     */
    public void togglePause() {
    	this.isPaused = ! this.isPaused;
    }
}