/** main class creating a board and the GUI
 * defines the game play
 */
public class TTTGame implements Game {

    /** currently active player */
    private int currentPlayer;

    /** total number of players */
    private int numPlayers;
    
    /** the board we play on */
    private TTTBoard board;
    
    /** the gui for board games */
    private UserInterface ui;
    
    /** constructor that copies a previous game */
    public TTTGame(TTTGame original) {
        this.currentPlayer = original.currentPlayer;
        this.numPlayers = original.numPlayers;
        this.board = new TTTBoard(original.board);
    }

    /** constructor that gets the number of players */
    public TTTGame(int numPlayers) {
        this.currentPlayer = 1;
        this.numPlayers = numPlayers;
        this.board = new TTTBoard(numPlayers);
    }

    @Override
    public String getTitle() {
        return this.numPlayers+"-way Tic Tac Toe";
    }

    @Override
    public void addMove(Coordinate pos) {
        this.board.addMove(pos, this.currentPlayer);
        if (this.currentPlayer == this.numPlayers) {
            this.currentPlayer = 1;
        } else {
            this.currentPlayer++;
        }
    }

    @Override
    public String getContent(Coordinate pos) {
        String result = "";
        int player = this.board.getPlayer(pos);
        if (player > 0) {
            result += player;
        }
        return result;
    }

    @Override
    public int getHorizontalSize() {
        return this.board.getSize();
    }

    @Override
    public int getVerticalSize() {
        return this.board.getSize();
    }

    @Override
    public void checkResult() {
        int status = this.getStatus();
        if (status >= 0) {
            this.ui.showResult(this.getStatusText(this.getStatus()));
        }
    }

    @Override
    public boolean isFree(Coordinate pos) {
        return this.board.isFree(pos);
    }

    @Override
    public void setUserInterface(UserInterface ui) {
        this.ui = ui;

    }

    public String toString() {
        return this.getStatusText(this.getStatus())+"\n"+this.board.toString();
    }

    @Override
    public int getStatus() {
        int winner = this.board.checkWinning();
        if (winner > 0) {
            return winner;
        }
        if (this.board.checkFull()) {
            return 0;
        }
        return -this.currentPlayer;
    }
    @Override
    public String getStatusText(int status) {
        if (status > 0) {
            return "Player "+status+" wins!";
        }
        if (status == 0) {
            return "This is a DRAW!";
        }
        return "Player "+-status+"'s move";
    }

}
