package jrummikub.model;

import java.util.ArrayList;

/** Class managing the overall and momentary RoundState */
public class RoundState implements IRoundState {
	private static final long serialVersionUID = 8678490099871939059L;

	private GameSettings gameSettings;
	private GameState gameState;

	private ITable table;
	private ArrayList<Player> players;
	private int activePlayer;
	private StoneHeap stoneHeap;
	private IPlayer lastPlayer;
	private int turnNumber;

	/**
	 * Create a new RoundState with an empty table
	 * 
	 * @param gameSettings
	 *          the game settings
	 * @param gameState
	 *          the game state
	 */
	public RoundState(GameSettings gameSettings, GameState gameState) {
		this.gameSettings = gameSettings;
		this.gameState = gameState;

		table = new Table(gameSettings);
		players = new ArrayList<Player>();

		for (PlayerSettings playerSettings : gameSettings.getPlayerList()) {
			players.add(new Player(playerSettings));
		}

		turnNumber = 1 - gameSettings.getPlayerList().size();

		activePlayer = 0;
		stoneHeap = new StoneHeap(gameSettings);
	}

	@Override
	public ITable getTable() {
		return table;
	}

	@Override
	public void setTable(ITable table) {
		this.table = table;
	}

	@Override
	public int getPlayerCount() {
		return players.size();
	}

	@Override
	public void nextPlayer() {
		activePlayer = (activePlayer + 1) % players.size();
	}

	@Override
	public void setActivePlayerNumber(int i) {
		int j = i % players.size();
		if (j < 0) {
			j += players.size();
		}
		activePlayer = j;
	}

	@Override
	public IPlayer getNthNextPlayer(int i) {
		int j = (activePlayer + i) % players.size();
		if (j < 0) {
			j += players.size();
		}
		return players.get(j);
	}

	@Override
	public IPlayer getNthPlayer(int i) {
		int j = i % players.size();
		if (j < 0) {
			j += players.size();
		}
		return players.get(j);
	}

	@Override
	public IPlayer getActivePlayer() {
		return players.get(activePlayer);
	}

	@Override
	public StoneHeap getStoneHeap() {
		return stoneHeap;
	}

	@Override
	public GameSettings getGameSettings() {
		return gameSettings;
	}

	@Override
	public void setLastPlayer(IPlayer lastPlayer) {
		this.lastPlayer = lastPlayer;
	}

	@Override
	public IPlayer getLastPlayer() {
		return lastPlayer;
	}

	@Override
	public int getTurnNumber() {
		return turnNumber;
	}

	@Override
	public void nextTurn() {
		turnNumber++;
	}

	@Override
	public GameState getGameState() {
		return gameState;
	}
}
