import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

/**
 * The controller for Calaveras Crossing.  The controller handles the time and
 * the player's input.
 *
 * @author Jim Glenn
 * @version 0.1 10/7/2008
 */

public class CalaverasCrossingControl extends KeyAdapter
{
    /**
     * The game model this controller is connected to.
     */

    private CalaverasCrossingGame game;

    /**
     * The game view this controller is connected to.
     */

    private CalaverasCrossingPanel view;

    /**
     * Whether we have given the panel the focus.
     */

    private boolean gotFocus;

    /**
     * Creates a CalaverasCrossing controller connected to the given game model and
     * view.
     *
     * @param g a CalaverasCrossing game
     * @param p a panel displaynig a CalaverasCrossing game
     */

    public CalaverasCrossingControl(CalaverasCrossingGame g, CalaverasCrossingPanel p)
    {
	game = g;
	view = p;

	gotFocus = false;

	Timer t = new Timer(1000 / 20,
			    new ActionListener() {
				public void actionPerformed(ActionEvent e)
				{
				    timerTick();
				}
			    });
	t.start();
    }

    /**
     * Handles timer events.
     */

    public synchronized void timerTick()
    {
	game.update();
	view.repaint();

	if (!gotFocus)
	    {
		view.requestFocus();
		gotFocus = true;
	    }
    }

    public void keyPressed(KeyEvent e)
    {
	if (e.getKeyCode() == KeyEvent.VK_UP)
	    game.getPlayerFrog().startJump(Frog.UP);
	else if (e.getKeyCode() == KeyEvent.VK_DOWN)
	    game.getPlayerFrog().startJump(Frog.DOWN);
	else if (e.getKeyCode() == KeyEvent.VK_LEFT)
	    game.getPlayerFrog().startJump(Frog.LEFT);
	else if (e.getKeyCode() == KeyEvent.VK_RIGHT)
	    game.getPlayerFrog().startJump(Frog.RIGHT);
    }
}

