package jrummikub.control.network;

import java.util.UUID;

import jrummikub.model.GameSettings;
import jrummikub.util.Event;
import jrummikub.util.GameData;
import jrummikub.util.IEvent;
import jrummikub.util.IListener;
import jrummikub.util.IListener1;
import jrummikub.view.ISettingsPanel.SettingsMode;
import jrummikub.view.IView;

/**
 * Control for joining a network game
 */
public class GameJoinControl extends AbstractGameBeginControl {
	private Event gameStartEvent = new Event();

	/**
	 * Creates new game join control
	 * 
	 * @param connectionControl
	 *          the current connection control for events and messages
	 * @param gameData
	 *          the game data for settings, game id
	 * @param view
	 *          the view
	 */
	public GameJoinControl(final IConnectionControl connectionControl,
			final GameData gameData, final IView view) {
		super(connectionControl, view, gameData, SettingsMode.NETWORK_JOIN);

		NetworkControl.fixGameSettings(gameData.getGameSettings(), connectionControl.getNickname());
		updateSettingsPanel();

		connections.add(connectionControl.getGameOfferEvent().add(
				new IListener1<GameData>() {
					@Override
					public void handle(GameData data) {
						if (data.getGameID().equals(gameData.getGameID())) {
							GameSettings settings = data.getGameSettings();

							NetworkControl.fixGameSettings(settings, connectionControl.getNickname());

							gameData.setGameSettings(settings);

							updateSettingsPanel();
						}
					}
				}));

		connections.add(connectionControl.getGameWithdrawalEvent().add(
				new IListener1<UUID>() {
					@Override
					public void handle(UUID uuid) {
						if (uuid.equals(gameData.getGameID())) {
							abort();
							backEvent.emit();
						}
					}
				}));

		connections.add(connectionControl.getGameStartEvent().add(new IListener() {
			@Override
			public void handle() {
				abort();
				gameStartEvent.emit();
			}
		}));
	}

	/**
	 * The event that is emitted when the game is started
	 * 
	 * @return the event
	 */
	public IEvent getStartGameEvent() {
		return gameStartEvent;
	}

	/**
	 * Starts the join control and sets the settings panel in game join mode
	 */
	public void startGameJoin() {
		view.showSettingsPanel(true);
	}

	/**
	 * Aborts joining and goes back to game list
	 */
	@Override
	protected void goBack() {
		abort();
		connectionControl.leaveGame();
		backEvent.emit();
	}
}
