package jrummikub.control;

import jrummikub.model.IGameSettings;
import jrummikub.model.RoundState;
import jrummikub.util.IListener;
import jrummikub.view.IView;

/**
 * Controls a Game, at some point including all Rounds, starts new Rounds
 */
public class GameControl {
	private IGameSettings gameSettings;
	private IView view;
	private RoundControl roundControl;

	/**
	 * Constructor
	 * 
	 * @param gameSettings
	 *          the game settings
	 * @param view
	 *          the view
	 */
	public GameControl(IGameSettings gameSettings, IView view) {
		this.gameSettings = gameSettings;
		this.view = view;

		view.getNewGameEvent().add(new IListener() {
			@Override
			public void handle() {
				startRound();
			}
		});
		view.getQuitEvent().add(new IListener() {
			@Override
			public void handle() {
				quitProgram();
			}
		});
	}

	/**
	 * Game gets started by initializing the first Round
	 */
	public void startGame() {
		startRound();
	}

	private void startRound() {
		if (roundControl != null) {
			return;
		}

		RoundState roundState = new RoundState(gameSettings);

		roundControl = new RoundControl(roundState, view);
		roundControl.getEndRoundEvent().add(new IListener() {

			@Override
			public void handle() {
				roundControl = null;
			}
		});

		roundControl.startRound();
	}

	private void quitProgram() {
		System.exit(0);
	}

}
