package jrummikub.control.network;

import jrummikub.control.RoundControl;
import jrummikub.control.turn.ITurnControl;
import jrummikub.model.IHand;
import jrummikub.model.IRoundState;
import jrummikub.model.ITable;
import jrummikub.model.PlayerSettings.Type;
import jrummikub.util.IListener1;
import jrummikub.view.IView;

public class NetworkRoundControl extends RoundControl {
	private IConnectionControl connectionControl;
	private boolean currentlyActive;

	public NetworkRoundControl(IRoundState roundState, IView view,
			final IConnectionControl connectionControl, boolean startActive) {
		super(roundState, view);

		this.connectionControl = connectionControl;
		currentlyActive = startActive;

		connections.add(connectionControl.getTurnStartEvent().add(
				new IListener1<IRoundState>() {
					@Override
					public void handle(IRoundState state) {
						NetworkControl.fixGameSettings(state.getGameSettings(),
								connectionControl.getNickname());
						setRoundState(state);

						startTurn();
					}
				}));
	}

	@Override
	protected void addTurnControlListeners(ITurnControl turnControl) {
		turnControl.getTableUpdateEvent().add(new IListener1<ITable>() {
			@Override
			public void handle(ITable table) {
				connectionControl.updateTable(table);
			}
		});
	}

	@Override
	protected ITurnControl createTurnControl(Type type) {
		switch (type) {
			case HUMAN:
				currentlyActive = true;
				break;
			case NETWORK:
				currentlyActive = false;
				break;
		}

		if (!currentlyActive) {
			return new NetworkTurnControl(connectionControl);
		}

		return super.createTurnControl(type);
	}

	@Override
	protected void prepareTurn() {
		boolean wasActive = currentlyActive;

		doPrepareTurn();

		if (wasActive) {
			connectionControl.startTurn(roundState);
		}
	}

	@Override
	protected void endOfTurn(IHand oldHand, ITable oldTable, ITable newTable) {
		if (currentlyActive) {
			connectionControl.endTurn(oldHand, oldTable, newTable);
		}

		super.endOfTurn(oldHand, oldTable, newTable);
	}
}
