package com.test.gwt.client;

import com.test.gwt.shared.UserDTO;

import jdk.management.resource.internal.inst.WindowsAsynchronousFileChannelImplRMHooks;

import java.util.Date;

import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.core.client.GWT;
import com.google.gwt.core.client.ScriptInjector;
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.resources.client.ClientBundle;
import com.google.gwt.resources.client.TextResource;
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.HTML;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.RootPanel;
import com.google.gwt.user.client.ui.TextBox;
import com.google.gwt.user.client.ui.PasswordTextBox;
import com.google.gwt.user.client.ui.VerticalPanel;
import com.google.gwt.user.client.ui.Widget;

import gwt,react.client.api.GwtReact;
import gwt.react.client.api.React;
import gwt.react.client.api.ReactDOM;
import gwt.react.client.components.ClassicComponentClass;
import gwt.react.client.events.MouseEventHandler;
import gwt.react.client.proptypes.BaseProps;
import gwt.react.client.utils.ObjLiteral;
import gwt.react_examples.redux.counter.client.components.Counter;
import gwt.react_examples.redux.counter.client.reducers.CounterReducer;
import gwt.redux.client.Action;
import gwt.redux.client.Redux;
import gwt.redux.client.Store;




/**
 * Entry point classes define <code>onModuleLoad()</code>.
 */
public class TestGWT 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.";

	/**
	 * Create a remote service proxy to talk to the server-side Greeting service.
	 */
	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();
    }
	
	
	private final LoginServiceAsync loginService = GWT.create(LoginService.class);

	/**
	 * This is the entry point method.
	 */
	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();
	final Label errorLabel = new Label();
	
	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)
    {
        loginService.loginFromSessionServer(new AsyncCallback<UserDTO>()
        {
            @Override
            public void onFailure(Throwable caught)
            {
                displayLoginWindow(true);
            }
     
            @Override
            public void onSuccess(UserDTO result)
            {
                if (result == null)
                {
                    displayLoginWindow(true);
                } else
                {
                    if (result.getLoggedIn())
                    {
                    	displayLoginWindow(false);
                    	loggedUserInfo.setText("Current logged in user: " + result.getUserName());
                        
                    } else
                    {
                        displayLoginWindow(true);
                    }
                }
            }
     
        });
    
    }
	
	public void onModuleLoad() {
		
		ScriptInjector.fromString(JsClientBundle.INSTANCE.gwtreactbundlejs().getText()).inject();
		ScriptInjector.fromString(JsClientBundle.INSTANCE.gwtreactrouterbundlejs().getText()).inject();
		
		
		// GWTReactBundleWrapper.injectScript();
		// Add the nameField and sendButton to the RootPanel
		// Use RootPanel.get() to get the entire body element
		RootPanel.get("userNameFieldContainer").add(userNameField);
		RootPanel.get("passwordFieldContainer").add(passwordField);
		RootPanel.get("loginButtonContainer").add(loginButton);
		RootPanel.get("errorLabelContainer").add(errorLabel);
		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)
	    {
	    	displayLoginWindow(true);
	    	
	    } else
	    {
	        checkWithServerIfSessionIdIsStillLegal(sessionID);
	    }

	    
		// 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) {
			    	Window.Location.replace("http://127.0.0.1:3000");
			    }
				
			}

			/**
			 * 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 10s expiry.
                            String sessionID = result.getSessionId();
                            final long DURATION = 1000 * 60 * 10;
                            Date expires = new Date(System.currentTimeMillis() + DURATION);
                            Cookies.setCookie("sid", sessionID, expires, null, "/", false);
                            displayLoginWindow(false);
                            loggedUserInfo.setText("Current logged in user: " + result.getUserName());
                        } else
                        {
                            Window.alert("Access Denied 1. Check your user-name and password.");
                        }
 
                    }
 
                    @Override
                    public void onFailure(Throwable caught)
                    {
      
                        Window.alert("Access Denied 2. Check your user-name and password.");
                    }
                });

			}
		}

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

	}
}
