package jrummikub.control;

import java.util.ArrayList;
import java.util.List;

import jrummikub.util.Connection;
import jrummikub.util.Event;
import jrummikub.util.Event1;
import jrummikub.util.IEvent;
import jrummikub.util.IEvent1;
import jrummikub.util.IListener;
import jrummikub.util.IListener1;
import jrummikub.util.LoginData;
import jrummikub.view.IView;

/**
 * Control checking and processing login data for network game
 * 
 */
public class LoginControl {
	private ApplicationControl appControl;
	private IView view;
	private Event1<LoginData> loginEvent = new Event1<LoginData>();
	private Event cancelEvent = new Event();
	private List<Connection> connections = new ArrayList<Connection>();

	/**
	 * Constructor for login Control
	 * 
	 * @param view
	 *            for events which need handling
	 * @param applicationControl 
	 * 			  the application control
	 */
	public LoginControl(final IView view, ApplicationControl applicationControl) {
		this.appControl = applicationControl;
		this.view = view;
		connections.add(view.getLoginPanel().getLoginEvent()
				.add(new IListener1<LoginData>() {
					@Override
					public void handle(LoginData loginData) {
						abort();
						appControl.updateDedicatedServerPassword(loginData);
						loginEvent.emit(loginData);
					}
				}));

		connections.add(view.getLoginPanel().getCancelEvent()
				.add(new IListener() {
					@Override
					public void handle() {
						abort();
						cancelEvent.emit();
					}
				}));
		connections.add(view.getLoginPanel().getUseDedicatedServerEvent().add(new IListener1<String>() {
			@Override
			public void handle(String value) {
				appControl.startDedicatedServer(value);
			}
		}));
	}

	/**
	 * Open Login panel
	 * 
	 * @param reset
	 *            when true resets the information in the login panel
	 */
	public void startLogin(boolean reset) {
		if (reset) {
			view.resetLoginPanel();
		}
		view.showLoginPanel(true);
	}

	/**
	 * Getter for loginEvent
	 * 
	 * @return loginEvent
	 */
	public IEvent1<LoginData> getLoginEvent() {
		return loginEvent;
	}

	/**
	 * Getter for cancelEvent
	 * 
	 * @return cancelEvent
	 */
	public IEvent getCancelEvent() {
		return cancelEvent;
	}

	/**
	 * Control abortion once all login data have been processed or login was
	 * canceled
	 * 
	 */
	public void abort() {
		view.showLoginPanel(false);
		for (Connection c : connections) {
			c.remove();
		}
	}
}
