package tictactoe.trans;
import tictactoe.pres.TTTFrame;
import tictactoe.app.*;
import util.*;
import java.awt.event.*;
import java.io.Serializable;
import javax.swing.*;

/**
 * An ActionListener which interprets input from a <code>TTTFrame</code>
 * and invokes the appropriate methods of the application components.
 * This class forms the translation component of a Tic-Tac-Toe application.
 *
 * @author Thomas P. Hayes
 * @version 1.0
 */
public class TTTHandler implements ActionListener, Serializable {

    public static final int EMPTY = 0;
    public static final int EX = 1;
    public static final int OH = 2;
    public TTTApplication gameApp;
    public TTTFrame gameFrame;

    public TTTHandler(TTTFrame f, TTTApplication app) {
	gameFrame = f;
	gameApp = app;
	f.addActionListener(this);
	app.setHandler(this);
    }
    
    public void actionPerformed (ActionEvent e) {
	String command = e.getActionCommand();
	Debug.print("Command=" + command + ".");
	if (command.startsWith("TTT")) {
	    command = command.substring(3);
	    if (command.equals("Finalize"))
		gameFrame.finalize(true);
	    else if (command.equals("New Game"))
		gameApp.resetBoard();
	    else if (command.equals("Quit")) 
		;
	    else if (command.equals("RealQuit"))
		System.exit(0);
	    else try {
		int buttonIndex = Integer.parseInt(command);
		if ((buttonIndex < 0) || (buttonIndex >=9))
		throw new NumberFormatException();
	    gameApp.makeMove(buttonIndex);
	    } catch (NumberFormatException nfe) {
		Debug.print("TTTHandler: received ActionCommand which is not a valid number in [0,8].");
	    }
	}
    }
    
    public void setMover (int code) {
	gameFrame.setMover(code);
    }
    
    public void enableMove (int where, boolean moveAllowed) {
	gameFrame.enableMove(where, moveAllowed);
    }
    
    public void displayMove (int where, int who) {
	if (who == EMPTY)
	    gameFrame.enableMove(where,true);
	else
	    gameFrame.enableMove(where, false);
    }

    public void wonGame (int who) {
	if (who == EX) {
	    JOptionPane.showMessageDialog(gameFrame,"X wins!");
	} else if (who == OH) {
	    JOptionPane.showMessageDialog(gameFrame,"O wins!");
	}
    }
}














