package com.torn.game;

import com.torn.player.Player;
import com.torn.table.Mark;
import com.torn.table.Table;


public class Game {

	private static Game game;

	/* 進行中のゲーム情報 */
	private Table table;
	private Player player1;
	private Player player2;
	private Player activePlayer;
	private Mark isFinishedMark;

	private Game() {
		initGame();
	}

	/* 初期化処理 */
	public void initGame() {
		table = null;
		isFinishedMark = null;
	}

	public static Game getInstance() {
		if (null == game) {
			game = new Game();
		}
		return game;
	}

	/* とりあえずの実装 */
	private boolean registPlayer(Player p) {
		if (null == player1) {
			player1 = p;
		} else if (null == player2) {
			player2 = p;
		} else {
			/* ２人まで登録可 */
			return false;
		}
		return true;
	}

	/* TODO:公開対象が大き過ぎないか検討 */
	public Table getTable() {
		if (null == table) {
			table = new Table();
		}
		return table;
	}

	private void prepareActivePlayer() {
		if (null == activePlayer) {
			if (null == player1) {
				registPlayer(new Player(Mark.MARU));
			}
			activePlayer = player1;
		}
	}

	public boolean putMark(int x, int y) {
		prepareActivePlayer();
		return table.put(activePlayer.getMark(), x, y);
	}

	public void turnEnd() {
		/* ゲーム終了判定 */
		if (null != table) {
			Mark mark = table.isFinished();
			if (null == mark) {
				/* do nothing */
			} else {
				isFinishedMark = mark;	
				if (Mark.EMPTY == mark) {
					System.out.println("引き分け");
				} else {
					System.out.println(activePlayer.getMark().toString() + "の勝利");
				}
				System.out.println("ゲーム終了");
				System.out.println("----------");
				return;
			}
		}
		/* ターン終了処理 */
		if (null == player2) {
			player2 = new Player(Mark.BATU);
		}
		activePlayer = (activePlayer == player1) ? player2 : player1;
	}

	/* @return 未終了時null */
	public Mark isFinished() {
		return isFinishedMark;
	}
}