package com.gwt.app.client;

import com.gwt.app.client.components.EmbeddedReact;
import com.gwt.app.shared.UserDTO;
import java.util.Date;
import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.core.client.GWT;
import com.google.gwt.dom.client.Document;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.dom.client.KeyCodes;
import com.google.gwt.event.dom.client.KeyUpEvent;
import com.google.gwt.event.dom.client.KeyUpHandler;
import com.google.gwt.user.client.Cookies;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.PasswordTextBox;
import com.google.gwt.user.client.ui.RootPanel;
import com.google.gwt.user.client.ui.TextBox;
import com.google.gwt.user.client.ui.Widget;
import gwt.react.client.api.React;
import gwt.react.client.api.ReactDOM;
import gwt.react.client.events.MouseEventHandler;
import gwt.react.client.events.MouseEvent;

/**
 * Entry point classes define <code>onModuleLoad()</code>.
 */
public class GWTReactApp implements EntryPoint {
	/**
	 * The message displayed to the user when the server cannot be reached or
	 * returns an error.
	 */
	private static final String SERVER_ERROR = "An error occurred while "
			+ "attempting to contact the server. Please check your network " + "connection and try again.";


	/**
	 * Inject gwt-react library script
	 */
	/*public interface JsClientBundle extends ClientBundle {
		final JsClientBundle INSTANCE = GWT.create(JsClientBundle.class);

        @Source("resources/gwt-react-bundle.min.js")
        TextResource gwtreactbundlejs();
        @Source("resources/gwt-react-router-bundle.min.js")
        TextResource gwtreactrouterbundlejs();
    }
	 */

	/**
	 * Create a remote service proxy to talk to the server-side Login service.
	 */
	private final LoginServiceAsync loginService = GWT.create(LoginService.class);

	final TextBox userNameField = new TextBox();
	final TextBox passwordField = new PasswordTextBox();
	final Button loginButton = new Button("LOGIN");
	final Button goToReactButton = new Button("GO TO REACT APP");
	final Label loggedUserInfo = new Label();

	private void setLoginFormVisibility(boolean displayLoginForm){
		RootPanel.get("loginFormDiv").setVisible(displayLoginForm);
		RootPanel.get("loggedInDiv").setVisible(!displayLoginForm);
	}

	private void setReactComponentVisibility(boolean displayReactComponent){
		RootPanel.get("gwtAppDiv").setVisible(!displayReactComponent);
		RootPanel.get("reactAppDiv").setVisible(displayReactComponent);
	}

	private void setLoggedInUserInfo(String username){
		loggedUserInfo.setText("Current logged in user: " + username);
	}

	private void displayLoginWindow(boolean displayLogin){
		// Hide info and React button
		if(displayLogin)
			loggedUserInfo.setText("");

		goToReactButton.setVisible(!displayLogin);
		RootPanel.get("userNameFieldLabel").setVisible(displayLogin);
		RootPanel.get("passwordFieldLabel").setVisible(displayLogin);
		userNameField.setVisible(displayLogin);
		passwordField.setVisible(displayLogin);
		loginButton.setVisible(displayLogin);
	}

	private void checkWithServerIfSessionIdIsStillLegal(String sessionID, boolean goToReactApp)
	{
		loginService.loginFromSessionServer(new AsyncCallback<UserDTO>()
		{
			@Override
			public void onFailure(Throwable caught)
			{
				setLoginFormVisibility(true);
				Window.alert(SERVER_ERROR);
			}

			@Override
			public void onSuccess(UserDTO result)
			{
				if (result == null)
				{
					setLoginFormVisibility(true);
				} else
				{
					if (result.getLoggedIn())
					{
						if(!goToReactApp){
							setLoginFormVisibility(false);
							setLoggedInUserInfo(result.getUserName());
						}
						else{
							setReactComponentVisibility(true);
							EmbeddedReact.ReactComponentProps componentProps = new EmbeddedReact.ReactComponentProps();

							componentProps.onGoToGWTAppClicked = new MouseEventHandler() {

								@Override
								public void onMouseEvent(MouseEvent event) {
									setReactComponentVisibility(false);
									String sessionID = Cookies.getCookie("sid");
									if (sessionID == null)
										setLoginFormVisibility(true);
									else
										checkWithServerIfSessionIdIsStillLegal(sessionID, false);

								}
							}; 
							componentProps.currentLoggedUser = result.getUserName();
							ReactDOM.render(React.createElement(EmbeddedReact::loggedInComponent, componentProps), Document.get().getElementById("reactAppDiv"));
						}

					} else
					{
						displayLoginWindow(true);
					}
				}
			}

		});

	}

	/**
	 * This is the entry point method.
	 */
	@Override
	public void onModuleLoad() {
		RootPanel.get("userNameFieldContainer").add(userNameField);
		RootPanel.get("passwordFieldContainer").add(passwordField);
		RootPanel.get("loginButtonContainer").add(loginButton);
		RootPanel.get("loggedInUserInfoContainer").add(loggedUserInfo);
		RootPanel.get("goToReactApplicationButtonContainer").add(goToReactButton);

		// Focus the cursor on the name field when the app loads
		userNameField.setFocus(true);
		userNameField.selectAll();

		String sessionID = Cookies.getCookie("sid");
		if (sessionID == null)
			setLoginFormVisibility(true);
		else
			checkWithServerIfSessionIdIsStillLegal(sessionID, false);

		// Create a handler for the sendButton and nameField
		class MyHandler implements ClickHandler, KeyUpHandler {
			/**
			 * Fired when the user clicks on the sendButton.
			 */
			public void onClick(ClickEvent event) {
				Widget sender = (Widget) event.getSource();
				if (sender == loginButton) {
					loginUser();
				} else if (sender == goToReactButton) {
					String sessionID = Cookies.getCookie("sid");
					if (sessionID == null)
						setLoginFormVisibility(true);
					else
						checkWithServerIfSessionIdIsStillLegal(sessionID, true);
				}

			}

			/**
			 * Fired when the user types in the nameField.
			 */
			public void onKeyUp(KeyUpEvent event) {
				if (event.getNativeKeyCode() == KeyCodes.KEY_ENTER) {
					loginUser();
				}
			}

			private void loginUser(){

				loginService.loginServer(userNameField.getValue(), passwordField.getValue(), new AsyncCallback<UserDTO>()
				{
					@Override
					public void onSuccess(UserDTO result)
					{

						if (result.getLoggedIn())
						{
							//Set session cookie for 60s
							String sessionID = result.getSessionId();
							final long DURATION = 1000 * 10;
							Date expires = new Date(System.currentTimeMillis() + DURATION);
							Cookies.setCookie("sid", sessionID, expires, null, "/", false);
							setLoginFormVisibility(false);
							setLoggedInUserInfo(result.getUserName());
						} else
						{
							Window.alert(SERVER_ERROR);
						}

					}

					@Override
					public void onFailure(Throwable caught)
					{

						Window.alert(SERVER_ERROR);
					}
				});

			}
		}

		// Add a handler to send the name to the server
		MyHandler handler = new MyHandler();
		loginButton.addClickHandler(handler);
		passwordField.addKeyUpHandler(handler);
		goToReactButton.addClickHandler(handler);		
	}
}
