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

define(['hp/model/Session',
        'hp/presenter/LoginPresenter',
        'hp/core/Router',
        'hp/core/Localizer',
        'hp/core/Validator',
        'hp/lib/jquery.hpTooltip',
        'lib/jquery.selectBox',
        'modernizr'],
function(session, presenter, router, localizer) {"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 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;

            /**
             * 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 = errorInfo.errorMessage +
                    (errorInfo.resolution ? ' ' + errorInfo.resolution : '');
                if(msg === 'undefined') {
                    msg = localizer.getString('login.loginUnsuccessful');
                }
                $(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).addClass(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;
            }

            /*
             * 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);
                } else {
                    $(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');
                    }
                }
            }
            
            //Since IE9 does not understand placeholder text
            function registerPlaceholderClick() {
                if (! Modernizr.input.placeholder) {
                    $(USER).parents('.hp-form-item').find('label:first').on('click', function () { 
                        if ($(USER).val() === '') {
                            $(USER).focus(); 
                        }
                    });
                    $(PASSWORD).parents('.hp-form-item').find('label:first').on('click', function () { 
                        if ($(PASSWORD).val() === '') {
                            $(PASSWORD).focus(); 
                        }
                    });
                }
            }
            /**
             * 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();
                });
                $(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();
                registerPlaceholderClick();
                /*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();
                registerPlaceholderClick();
                //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;
});
