// (C) Copyright 2020 Hewlett-Packard Enterprise Company, L.P.

define(['hp/model/Session',
        'hp/presenter/LoginPresenter',
        'hp/core/Router',
        'hp/core/Localizer',
		'hp/view/DialogView',
		'text!hpsumpages/common/shutdown.html',
        'hp/core/Validator',
        'hp/lib/jquery.hpTooltip',
        'lib/jquery.selectBox',
        'modernizr'],
function(session, presenter, router, localizer,DialogView,shutdownHtml) {"use strict";

    var LoginView = ( function() {

        var TITLE = '.hp-login-header';
        var SUB_TITLE = '.hp-login-sub-header';
        var FORM = '#hp-login-form';
        var BUTTON = '#hp-login-button';
		var BUTTON_SET = '.hp-buttonset';
		var SHUTDOWN_BUTTON = '#hp-shutdown-button';
		var TOTAL_SESSIONS = '#shutdown-session-count';
		var MOUSEHOVER_SPAN = '#shutdown-hover-text';
        var SPINNER = '#hp-login-spinner';
        var USER = '#hp-login-user';
        var PASSWORD = '#hp-login-password';
        var DISABLED = 'hp-disabled';
        var STATUS = '#hp-login-status';
        var PROVIDER_SELECT ='#hp-authn-provider-select';
        var PROVIDER_LIST_ITEM = '#hp-authn-provider-list-item';
        var PROVIDER_NAME = '#hp-authn-provider-name';
        var PROVIDER_TEXT = '#hp-authn-provider-text';
        var BODY = '#hp-body-div';

        /**
         * @class View management for the Login page (singleton).
         * @type {LoginView}
         */
        function LoginView() {

            /**
             * The validator for our form.
             */
            //var validator;
            var locationContext; // where we should redirect to
            var loginTitle; // title to use on the page.
            var loginSubTitle;
			var attempt = 0; //keep tracks of failed login attempts.
			var shutdown = $(shutdownHtml);
            /**
             * Handler for a successful login.
             */
            function onLoginSuccess() {
                router.go(locationContext, 'successful login');
            }

            /**
             * Handler for a failed login.  Show the failure.
             *
             * @param {string} message The error message.
             */
            function onLoginError(errorInfo) {
                var msg;
                $(SPINNER).hide();
                $(BUTTON).removeClass(DISABLED);
                msg = '<label>' + errorInfo.statusText + '</label> ' +
                    (errorInfo.resolution ? '' + errorInfo.resolution : '');
                attempt ++;           
				if( attempt >= 3){
					loginAttempts(attempt);	
					attempt = 0;
				}
				else{
					$(STATUS).html(msg).show();
					$(PASSWORD).val('').focus();
					}
            }

            /**
             * Handle a server request for a password change.
             */
            function onPasswordChange() {
                // The server has told us that the user needs to change their
                // password before they can log in.  So, redirect to the page
                // for that.
                router.go('/initialPassword', 'server requests password change');
            }

            /**
             * Handler for a click on the Login button.
             */
            function onLoginButtonClick() {
                if ($(FORM).valid()) {
                    $(BUTTON).removeClass(DISABLED);
                    $(SPINNER).fadeIn();
                    var provider = null;
                    var providerId = $(PROVIDER_SELECT + " :selected").val();
                    if (providerId === "0") {
                        provider = "LOCAL";
                    } else {
                        provider = $(PROVIDER_SELECT + " :selected").text();
                    }
                    presenter.login($(USER).val(), $(PASSWORD).val(), provider, {
                        success: onLoginSuccess,
                        error: onLoginError,
                        passwordChange: onPasswordChange
                    });
                }
                return false;
            }
			
			/**
             * Handler for a click on the shutdown button.
             */
			var handlers = {
                success : function(data) {
                    // Note: an invalid token returns null
					var noOfSessions = data.hapi.no_of_sessions;
					if(noOfSessions == 1)
					{	
						$(TOTAL_SESSIONS,shutdown).html("Currently there is " +  noOfSessions + " session active.");
					}
					else 
					{
						if(noOfSessions == 0)
						{ noOfSessions = "no";}
						$(TOTAL_SESSIONS,shutdown).html("Currently there are " +  noOfSessions + " sessions active.");
					}
					
					var shutdowndialogcontents = shutdown;
					//localizer.localizeDom(shutdowndialogcontents);
					new DialogView({
						contents : shutdowndialogcontents,
						ok : function() {
					
						var shutdownHandlers = { 
							success:function()
							{
								window.location.hash = '#/login';
								if(noOfSessions == 1)
								{
									window.document.write("SUM Engine is still running. Redirecting to Login page.");
									window.location.reload(true);
								}
								else
								{
									window.document.write("SUM Engine is Shutdown. Please restart the engine to Login.");
								}
							},
							error:function(){
							//Log.error("Error shutting down the service");
							}
						};
		
					var data = { hapi: {
						force: 'true'
						}};
					//close hpsum session
					session.shutDown(data, shutdownHandlers);
		 
					
				},
				cancel : function() {
					return;
				}
			});
                },
                error : function(jqXHR) {
                    Log.error("Failed to retrieve no of sessions data.");
                }
            };
			
			/**
             * Handler for a click on the shutdown button.
             */
			function onShutdownButtonClick()
			{
				$(SPINNER).fadeIn();
				if ($(FORM).valid()) {
                    $(SHUTDOWN_BUTTON).addClass(DISABLED);
					 var provider = null;
                    var providerId = $(PROVIDER_SELECT + " :selected").val();
                    if (providerId === "0") {
                        provider = "LOCAL";
                    } else {
                        provider = $(PROVIDER_SELECT + " :selected").text();
                    }
					presenter.login($(USER).val(), $(PASSWORD).val(), provider, {
                    //session.authenticateUser($(USER).val(), $(PASSWORD).val(), {
                        success: onAuthenticateUserSuccess,
                        error: authForShutdownFailed,
                    });
                }
                return false;
			}			
			
			/*
			* Show an error as authentication failed.
			*/
			function authForShutdownFailed(errorinfo)
			{
				onLoginError(errorinfo);
				$(STATUS).html(localizer.getString('hpsum.common.shutdownRequestFailed')).show();
                $(PASSWORD).val('');
				$(SHUTDOWN_BUTTON).removeClass(DISABLED);
			}
			
			/*
			* function to proceed with shutdown in case valid user credentials provided, else show an error.
			*/
			function onAuthenticateUserSuccess()
			{
				$(SPINNER).hide();
				$(STATUS).html('').hide();
				session.numberOfSessions(handlers);
				$(SHUTDOWN_BUTTON).removeClass(DISABLED);
 			}
 			
			/*
			* function to handle failed attempts.
			*/
			
			function loginAttempts(attempt)
			{
				$(USER).val('');
					$(PASSWORD).val('');
					$(USER).attr('disabled', true);
					$(PASSWORD).attr('disabled', true);
					$(BUTTON).removeClass(DISABLED);
					$(STATUS).html('<label>' + localizer.getString('hpsum.common.loginDelayed') + '</label>').show();
					$(SHUTDOWN_BUTTON).addClass(DISABLED);	
					setTimeout(function(){
							$(USER).val('');
							$(PASSWORD).val('');
							$(USER).attr('disabled', false);
							$(PASSWORD).attr('disabled', false);
							$(BUTTON).removeClass(DISABLED);
							$(SHUTDOWN_BUTTON).removeClass(DISABLED);
							$(STATUS).hide();
							$(USER).focus();
							attempt = 0;
						}, 10000);	
			}
            /*
             * initialization successful after authentication global setting completes.
             */
            function initSuccess() {
                $(SPINNER).hide();
                $(STATUS).hide();
                document.title = loginTitle;
                $(USER).focus();
            }

            /*
             * Handle settings success event, without authentication cannot complete.
             */
            function onGetGlobalSettingsComplete() {
                $(PROVIDER_SELECT).selectBox({autoWidth: false});
                //add LOCAL to the selectbox if it is allowed
                var allowLocal = presenter.getAllowLocalUser();
                if (allowLocal.allowLocalLogin === true) {
                    if ($(PROVIDER_SELECT + ' option[value="0"]').length === 0){
                        $(PROVIDER_SELECT).append($("<option>", {value : "0"}).text(localizer.getString('login.LocalUser')));
                    }
                }

                //add other login domains(if any)-  if not already added
                var providerInfos = presenter.getProviderInfos();
                if (providerInfos) {
                    $.each(providerInfos, function(index, providerInfo)
                    {
                        if($(PROVIDER_SELECT + ' option[value=' + providerInfo.loginDomain + ']').length === 0){
                            $(PROVIDER_SELECT).append($("<option>", {value : providerInfo.loginDomain}).text(providerInfo.name));
                        }
                    });
                    if ($(PROVIDER_SELECT + ' option').length > 1) {
                        $(PROVIDER_LIST_ITEM).show();
                        $(PROVIDER_NAME).hide();
                    }
                    else if(($(PROVIDER_SELECT + ' option').length === 1) && !allowLocal.allowLocalLogin) {
                        $(PROVIDER_LIST_ITEM).hide();
                        $(PROVIDER_NAME).show();
                    }
                }
                //set the default login domain in the selectbox
                var defaultProvider = presenter.getDefaultProvider();
                $(PROVIDER_SELECT).val(defaultProvider.loginDomain);
                $(PROVIDER_SELECT).selectBox('reset');
                $(PROVIDER_TEXT).text(defaultProvider.name);
                initSuccess();
            }

            /*
             * format error message based on error info.
             */
            function formatNotificationDetails(errorInfo) {
                var failureNotificationDetails = "</br>" + errorInfo.errorMessage + "  " +
                (errorInfo.resolution === null ? "" : errorInfo.resolution);
                return failureNotificationDetails;
            }

            /*
             * Show message in notification area.
             */
            function displaySettingsNotificationDetails (message) {
                $(STATUS).html(message).show();
                $(SPINNER).hide();
            }

            /*
             * Display a notification message.
             */
            function displayNotifications (message, details) {
                var notificationDetailsMessage = message + details;
                displaySettingsNotificationDetails(notificationDetailsMessage);
            }


            /*
             * Handle error by displaying a message in the notification area.
             */
            function onError(error) {
                var failureNotificationDetails = formatNotificationDetails(error.errorInfo);
                displayNotifications(error.failureMessage, failureNotificationDetails);
            }


            /*
             * Set button state based on form.
             */
            function updateState() {
                if ($(USER).val() && $(PASSWORD).val()) {
                    $(BUTTON).removeClass(DISABLED);
					$(SHUTDOWN_BUTTON).removeClass(DISABLED);
                } else {
                    $(BUTTON).removeClass(DISABLED);
					$(SHUTDOWN_BUTTON).addClass(DISABLED);
                }
                if (! Modernizr.input.placeholder) {
                    if ($(USER).val() === '') {
                        $(USER).parents('.hp-form-item').addClass('hp-unset-inactive');
                    } else {
                        $(USER).parents('.hp-form-item').removeClass('hp-unset-inactive');
                    }
                    if ($(PASSWORD).val() === '') {
                        $(PASSWORD).parents('.hp-form-item').addClass('hp-unset-inactive');
                    } else {
                        $(PASSWORD).parents('.hp-form-item').removeClass('hp-unset-inactive');
                    }
                }
            }

            /**
             * Initialize the view.
             */
            this.init = function () {
                $(TITLE).text(loginTitle);
                if (loginSubTitle) {
                    $(SUB_TITLE).text(loginSubTitle);
                }
                $(USER).attr('placeholder', localizer.getString('core.login.user'));
                $(PASSWORD).attr('placeholder',
                    localizer.getString('core.login.password'));

                $(BUTTON).bind('click', function(ev) {
                    onLoginButtonClick.call(this);
                    ev.preventDefault();
                });
				
				
				$(BUTTON_SET).css({ display: "block" });
				$(BUTTON_SET).append("<button id='hp-shutdown-button' class='hp-button' style='float:right'></button>");
				$('#hp-shutdown-button').text(localizer.getString('hpsum.shutdown.shutdownButton'));
				 $(SHUTDOWN_BUTTON).bind('click', function(ev) {
                    onShutdownButtonClick.call(this);
					//Disable the default navigation of the shutdown button click
					ev.preventDefault();
				 });
				
				$(FORM).on('change input keydown keyup focus blur', 'input', updateState);
                // Modernizr can't detect oninput
                if ($('html.ie8').length > 0) {
                    $(FORM).on('paste', 'input', function () {
                        setTimeout(updateState, 10);
                    });
                }
                updateState();
                /*validator = $(FORM).validate({
                    errorPlacement: function(error, element) {
                        element.hpTooltip(error.text());
                    },
                    success: 'valid' // helps tooltip work right
                });*/
                $(PROVIDER_LIST_ITEM).hide();
                $(PROVIDER_NAME).hide();
                presenter.on("getGlobalSettingsComplete", onGetGlobalSettingsComplete);
                presenter.on("getGlobalSettingsError", onError);
                presenter.loadProvidersInfo();
				
				
            };

            /**
             * Returning to this page after being away.
             */
            this.resume = function() {
                $(SPINNER).hide();
                $(STATUS).hide();
                $(BODY).removeClass('hp-sessioned');
                $(USER).val('');
                $(PASSWORD).val('');
                updateState();
                //validator.resetForm();
                document.title = loginTitle;
                $(USER).focus();
            };

            /**
             * Stop displaying/updating this page.
             */
            this.pause = function() {
                $(SPINNER).hide();
            };

            this.setLocationContext = function(location) {
                locationContext = location;
            };

            this.setTitle = function(title, subTitle) {
                loginTitle = title;
                loginSubTitle = subTitle;
            };
        }

        return new LoginView();
    }());
    return LoginView;
});
