package szakdolgozat.client;

import szakdolgozat.client.servereventlistener.ServerEventsListener;
import szakdolgozat.client.serverevents.GameProposalEvent;
import szakdolgozat.client.serverevents.UserLoginEvent;
import szakdolgozat.client.serverevents.UserLogoutEvent;
import szakdolgozat.client.ui.GameProposalDialog;
import szakdolgozat.client.ui.InfoPanel;
import szakdolgozat.client.ui.LoginWindow;
import szakdolgozat.client.ui.RegisterWindow;
import szakdolgozat.client.ui.UserListWindow;
import szakdolgozat.client.ui.UserStatsWindow;
import szakdolgozat.client.ui.WaitingDialog;
import szakdolgozat.shared.User;
import szakdolgozat.shared.UserStats;

import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.event.logical.shared.ValueChangeEvent;
import com.google.gwt.event.logical.shared.ValueChangeHandler;
import com.google.gwt.user.client.DOM;
import com.google.gwt.user.client.History;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.Window.ClosingEvent;
import com.google.gwt.user.client.ui.DecoratedTabPanel;
import com.google.gwt.user.client.ui.HasHorizontalAlignment;
import com.google.gwt.user.client.ui.HasVerticalAlignment;
import com.google.gwt.user.client.ui.RootPanel;
import com.google.gwt.user.client.ui.VerticalPanel;

import de.novanic.eventservice.client.event.RemoteEventService;
import de.novanic.eventservice.client.event.RemoteEventServiceFactory;
import de.novanic.eventservice.client.event.domain.Domain;
import de.novanic.eventservice.client.event.domain.DomainFactory;

public class UI implements EntryPoint, ValueChangeHandler {

	public static DecoratedTabPanel loginAndRegisterDecoratedTabPanel;
	public static DecoratedTabPanel mainMenuDecoratedTabPanel;
	public static UserStatsWindow userStatsWindow;
	public static InfoPanel infoPanel;
	public RootPanel rootPanel;
	public static WaitingDialog waitingDialog;
	private final static Domain GAME_DOMAIN = DomainFactory
			.getDomain("gamedom");
	public static VerticalPanel verticalPanel;
	public static User currentUser;
	public static UserListWindow userListWindow;
	public static ServicesAsync servicesHandler = Services.ServerServiceHolder
			.getInstance();
	public static RemoteEventService theEventService = null;
	public static boolean isPlaying;

	@Override
	public void onModuleLoad() {
		rootPanel = RootPanel.get();
		rootPanel.setSize(Window.getClientWidth() - 20 + "px", Window
				.getClientHeight()
				- 20 + "px");

		verticalPanel = new VerticalPanel();
		verticalPanel.setVerticalAlignment(HasVerticalAlignment.ALIGN_MIDDLE);
		verticalPanel
				.setHorizontalAlignment(HasHorizontalAlignment.ALIGN_CENTER);
		rootPanel.add(verticalPanel);
		verticalPanel.setSize(Window.getClientWidth() - 20 + "px", Window
				.getClientHeight()
				- 20 + "px");

		History.addValueChangeHandler(this);

		if (History.getToken().isEmpty()) {
			History.newItem("login");
		} else {
			changePage(History.getToken());
		}

		// History.newItem("login");
		// Window.Location.assign(Window.Location.getPath()
		// + Window.Location.getQueryString() + "#login");
		// initLoginAndRegisterUI();

	}

	public static void initLoginAndRegisterUI() {
		loginAndRegisterDecoratedTabPanel = new DecoratedTabPanel();
		verticalPanel.add(loginAndRegisterDecoratedTabPanel);
		verticalPanel.setCellVerticalAlignment(
				loginAndRegisterDecoratedTabPanel,
				HasVerticalAlignment.ALIGN_MIDDLE);
		verticalPanel.setCellHorizontalAlignment(
				loginAndRegisterDecoratedTabPanel,
				HasHorizontalAlignment.ALIGN_CENTER);
		loginAndRegisterDecoratedTabPanel.setAnimationEnabled(true);

		LoginWindow loginWindow = new LoginWindow();
		loginAndRegisterDecoratedTabPanel.add(loginWindow, "Belépés", false);
		loginWindow.setSize("5cm", "3cm");

		RegisterWindow registerWindow = new RegisterWindow();
		loginAndRegisterDecoratedTabPanel.add(registerWindow, "Regisztráció",
				false);
		registerWindow.setSize("5cm", "3cm");
		loginAndRegisterDecoratedTabPanel.selectTab(0);
		loginWindow.userNameTextBox.setFocus(true);
		// Window.Location.assign("/login");
		if (DOM.getElementById("loading") != null)
			DOM.removeChild(RootPanel.getBodyElement(), DOM
					.getElementById("loading"));
	}

	public static void initMainMenuUI() {
		listenForGameproposals();
		mainMenuDecoratedTabPanel = new DecoratedTabPanel();
		mainMenuDecoratedTabPanel.setAnimationEnabled(true);
		verticalPanel.setCellHorizontalAlignment(mainMenuDecoratedTabPanel,
				HasHorizontalAlignment.ALIGN_CENTER);
		verticalPanel.add(mainMenuDecoratedTabPanel);
		verticalPanel.setCellVerticalAlignment(mainMenuDecoratedTabPanel,
				HasVerticalAlignment.ALIGN_MIDDLE);

		userListWindow = new UserListWindow();
		mainMenuDecoratedTabPanel.add(userListWindow, "Játékosok", false);
		userListWindow.setSize("5cm", "3cm");
		userListWindow.getUserListFromServer();
		// userListWindow.refreshTimer.scheduleRepeating(6000);
		// userListWindow.refreshUserList();
		userStatsWindow = new UserStatsWindow();
		mainMenuDecoratedTabPanel.add(userStatsWindow, "Saját statisztikák",
				false);
		userStatsWindow.setSize("5cm", "3cm");
		userStatsWindow.setUserStats(currentUser);

		infoPanel = new InfoPanel();
		verticalPanel.add(infoPanel);
		verticalPanel.setCellVerticalAlignment(infoPanel,
				HasVerticalAlignment.ALIGN_MIDDLE);
		verticalPanel.setCellHorizontalAlignment(infoPanel,
				HasHorizontalAlignment.ALIGN_CENTER);

		infoPanel.init();

		loginAndRegisterDecoratedTabPanel.selectTab(0);

		mainMenuDecoratedTabPanel.selectTab(0);
		Window.addWindowClosingHandler(new Window.ClosingHandler() {

			@Override
			public void onWindowClosing(ClosingEvent event) {
				InfoPanel.logout();
			}
		});
	}

	private static void listenForGameproposals() {
		RemoteEventServiceFactory theEventServiceFactory = RemoteEventServiceFactory
				.getInstance();
		theEventService = theEventServiceFactory.getRemoteEventService();

		theEventService.addListener(GAME_DOMAIN, new ServerEventsListener() {

			@Override
			public void onGameProposal(GameProposalEvent event) {
				if (event.getFrom().getUsername().equals(
						currentUser.getUsername())) {
					waitingDialog = new WaitingDialog();
					waitingDialog.center();
					userListWindow.userListGrid.hide();
				} else if (event.getTo().getUsername().equals(
						currentUser.getUsername())) {
					if (userListWindow.refuseProposalsCheckBox.getValue() == false) {
						new GameProposalDialog(event.getFrom(), event.getTo())
								.center();
						userListWindow.userListGrid.hide();
					} else
						GameProposalDialog.informOtherPlayer(false);
				}
			}

			@Override
			public void onUserLogout(UserLogoutEvent event) {
				for (User u : userListWindow.loggedinUsers)
					if (u.getId() == event.getUser().getId()) {
						userListWindow.loggedinUsers.remove(u);
						break;
					}

				for (UserStats us : userListWindow.userStats)
					if (us.getPlayerid() == event.getUser().getId()) {
						userListWindow.userStats.remove(us);
						break;
					}

				userListWindow.refreshUserList();
			}

			@Override
			public void onUserLogin(UserLoginEvent event) {
				if(event.getUser().getId() == currentUser.getId())
					return;
				userListWindow.loggedinUsers.add(event.getUser());
				userListWindow.userStats.add(event.getUserStats());
				userListWindow.refreshUserList();

			}

		});
	}

	@Override
	public void onValueChange(ValueChangeEvent event) {
		changePage(History.getToken());
	}

	public void changePage(String token) {
		if (History.getToken().equals("login")) {
			verticalPanel.clear();
			initLoginAndRegisterUI();
			if (theEventService != null)
				theEventService.removeListeners();
		} else if (History.getToken().equals("main")) {
			if (currentUser != null) {
				verticalPanel.clear();
				initMainMenuUI();
			} else {
				History.newItem("login");
			}
		} else {
			History.newItem("login");
		}
	}

}
