package com.horstmann.flip;

import java.awt.BorderLayout;

import javax.swing.JFrame;
import javax.swing.JTextField;

import edu.lhup.ai.IMove;
import edu.lhup.ai.IPlayer;

public class FlipFrame extends JFrame
{
    public FlipFrame(IPlayer player)
    {
        this.player = player;
        add(oldMove, BorderLayout.PAGE_START);
        setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
    }

    /**
     * Gets the next user command from the GUI
     * @return a string of the form: taken dice followed by "f" or "p" and a die
     * number, e.g. "112f4"
     */
    public String getInputString()
    {
        try
        {
            return panel.getInputString();
        }
        catch (InterruptedException ex)
        {
            ex.printStackTrace();
            return "";
        }
    }

    /**
     * Updates the GUI to reflect the current board
     * @param board the current flip board
     */
    public void updateDisplay(FlipBoard board)
    {
        if (panel == null)
        {
            panel = new FlipPanel(board, player);
            add(panel);
            pack();
        }
        setVisible(true);
        IMove move = board.peekMove();
        oldMove.setText(move == null ? "" : board.getPlayers()[1 - board
                .getTurn()]
                + ": " + move.toString());
        panel.updateBoard();
    }

    /**
     * Resets the display at the end of a game.
     */
    public void resetDisplay()
    {
        remove(panel);
        panel = null;
        setVisible(false);
    }

    private IPlayer player;
    private FlipPanel panel = null;
    private JTextField oldMove = new JTextField();
}
