package jrummikub.control.network;

import jrummikub.control.turn.AbstractTurnControl;
import jrummikub.model.IHand;
import jrummikub.model.IRoundState;
import jrummikub.model.ITable;
import jrummikub.util.Event1;
import jrummikub.util.IEvent1;
import jrummikub.util.IListener1;
import jrummikub.util.IListener3;

public class NetworkTurnControl extends AbstractTurnControl {
	private IConnectionControl connectionControl;
	private Event1<IRoundState> stateUpdateEvent = new Event1<IRoundState>();

	public NetworkTurnControl(IConnectionControl connectionControl) {
		this.connectionControl = connectionControl;
	}

	public IEvent1<IRoundState> getStateUpdateEvent() {
		return stateUpdateEvent;
	}

	@Override
	public void doStartTurn() {
		connections.add(connectionControl.getTableUpdateEvent().add(
				new IListener1<ITable>() {
					@Override
					public void handle(ITable table) {
						view.getTablePanel().setStoneSets(table);
					}
				}));
		connections.add(connectionControl.getTurnEndEvent().add(
				new IListener3<IHand, ITable, ITable>() {
					@Override
					public void handle(IHand oldHand, ITable oldTable, ITable newTable) {
						endOfTurn(oldHand, oldTable, newTable);
					}
				}));

		timer.startTimer();
	}

	private void endOfTurn(IHand oldHand, ITable oldTable, ITable newTable) {
		cleanUp();

		endOfTurnEvent.emit(oldHand, oldTable, newTable);
	}

	@Override
	protected void timeOut() {
	}

	@Override
	protected void pauseTurn() {
	}
}
