package swingUI;

import game.TicTacToeFrame;

import java.awt.GridLayout;
import java.awt.event.ActionEvent;

import javax.swing.AbstractAction;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingConstants;

import computer.Computer;


/**
 * @author martin
 *were the game is playing
 */
public class TicTacToeGame extends JPanel{
	/**
	 * @param nav as Jframe navigator
	 * @param game as the current game
	 * @param turn as turn number
	 */
	public TicTacToeGame(final TicTacToeNav nav, final TicTacToeFrame game, final char turn){
		super(new GridLayout(3, 3));
		setFocusable(true);

		for (int y=0;y<3;y++){
			for (int x=0;x<3;x++){
				if (game.getX(x, y)){
					add(new JLabel("X",SwingConstants.CENTER));
				}else if (game.getO(x, y)){
					add(new JLabel("O",SwingConstants.CENTER));
				}else{
					add(new JButton(makeAction(x,y,nav, game, turn)));
				}
			}
		}
	}

	/**
	 * action creator for each button
	 * @param x as coordinate
	 * @param y as coordinate
	 * @param nav as jframe navigator
	 * @param game as current game
	 * @param turn as game turn
	 * @return new costum action
	 */
	private AbstractAction makeAction(final int x, final int y, final TicTacToeNav nav, final TicTacToeFrame game, final char turn){
		if (turn == 'X')
			return new AbstractAction(){
				public void actionPerformed(ActionEvent e) {
					try {
						if (game.setX(x, y).getWinnerX())
							nav.win();
						else if(game.setX(x,y).endGame())
							nav.stat();
						else
							nav.game(new TicTacToeGame(nav, game.setX(x, y), 'O'));
					} catch (Exception e1) {
						nav.title();
					}
				}
			};
		else if(turn == 'O')
			return new AbstractAction(){
				public void actionPerformed(ActionEvent e) {
					try {
						if (game.setO(x, y).getWinnerO())
							nav.win();
						else if(game.setO(x,y).endGame())
							nav.stat();
						else
							nav.game(new TicTacToeGame(nav, game.setO(x, y), 'X'));
					} catch (Exception e1) {
						nav.title();
					}
				}
		};
		else{
			return new AbstractAction(){
				public void actionPerformed(ActionEvent e) {
						try {
							if (game.setX(x, y).getWinnerX())
								nav.win();
							else if(game.setX(x,y).endGame())
								nav.stat();
							else{
								TicTacToeFrame tmpGame = game.setX(x, y);
								tmpGame = tmpGame.setO(Computer.getSolution(tmpGame, false),0);
								if(tmpGame.getWinnerO() || tmpGame.endGame())
									nav.stat();
								else
									nav.game(new TicTacToeGame(nav, tmpGame, 'S'));
							}
						} catch (Exception e1) {
							nav.title();
						}
				}
			};
		}
	}

}
