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

define(['hp/model/Session',
        'hp/presenter/LoginPresenter',
        'hp/core/Router',
        'hp/view/FormStateView',
        'hp/core/Localizer',
        'hp/core/Validator'
        ],
function(session, presenter, router, FormStateView, localizer) {

    var InitialPasswordView = ( function() {

        var TITLE = '.hp-initial-password-header',
            FORM = '#hp-initial-password-form',
            BUTTON = '#hp-initial-password-button-element',
            SPINNER = '#hp-initial-password-spinner',
            USER = '#hp-initial-password-user',
            PASSWORD1 = '#hp-initial-password-new1',
            PASSWORD2 = '#hp-initial-password-new2',
            MIN_PASSWORD_LENGTH = 8,
            PASSWORD_CHANGE_STATUS = '#hp-password-change-status',
            DISABLED = 'disabled';
        var formStateView = new FormStateView();

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

            /**
             * The validator for our form.
             */
            var validator;
            var locationContext; // where we should redirect to
            var loginTitle; // title to use on the page.
            var validPasswdLength = localizer.getString('login.initialPassword.checkLength');
            var validMatchPasswd = localizer.getString('login.initialPassword.matchpasswd');
            var validPassword = localizer.getString('login.initialPassword.passwordValidation');
            var isSubmitted;


            function reset(){
                validator.resetForm();
                formStateView.reset();
            }

            /**
             * Handler for a successful login.
             */
            function onInitialPasswordSuccess() {
                reset();
                router.go(locationContext, 'successfully set initial password');
            }

            /**
             * Handler for a failed password change.  Show the failure.
             *
             * @param {string} message The error message.
             */
            function onInitialPasswordError(errorInfo) {
                $(SPINNER).hide();
                $(BUTTON).removeAttr(DISABLED);
                var msg = '<label>' + errorInfo.errorMessage + '</label> ' +
                (errorInfo.resolution ? '' + errorInfo.resolution : '');
                $(PASSWORD_CHANGE_STATUS).html(msg).show();
                reset();

            }

            /**
             * Handler for a password change request from the server.
             */
            function onPasswordChange() {
                // OK.  The user tried to log in, and the server said he had
                // to change his password.  We collected a new password and
                // sent the request to change it, and that succeeded.  Then we
                // tried to log in with the new password, and the server
                // requested another password change.  This shouldn't happen.
                // We'll punt them back to the login page.
                reset();
                router.go('/login');
            }

            /**
             * Handler for a click on the OK button.
             */
            function onOKButtonClick() {
                if ($(FORM).valid() && isSubmitted == false) {
                    isSubmitted = true;
                    $(BUTTON).attr(DISABLED, DISABLED);
                    $(SPINNER).fadeIn();
                    presenter.setInitialPassword($(PASSWORD1).val(), {
                        success: onInitialPasswordSuccess,
                        error: onInitialPasswordError,
                        passwordChange: onPasswordChange
                    });
                }
                return false;
            }

            function initForm(){
                isSubmitted = false;
                validator = $(FORM).validate({
                    rules : {
                        hpinitialpasswordnew1 : {
                            required : true,
                            cicUsersEditCheckPasswdString : PASSWORD1,
                            cicUsersEditCheckPwdLength : MIN_PASSWORD_LENGTH
                        },
                        hpinitialpasswordnew2 : {
                            cicUsersEditMatchPasswd : PASSWORD1
                        }
                    }
                });
                $.validator.addMethod("cicUsersEditCheckPwdLength",
                    function(value, element, param) {
                        return ((value.length >= 8));
                    },
                    validPasswdLength
                );
                $.validator.addMethod("cicUsersEditMatchPasswd",
                    function(value, element, param) {
                        // bind to the blur event of the target in order to revalidate whenever the target field is updated
                        var target = $(param).unbind(".validate-equalTo").bind("blur.validate-equalTo",
                            function() {
                                $(element).valid();
                            }
                        );
                        var result = (value === target.val());
                        return result;
                    },
                    validMatchPasswd
                );
                $.validator.addMethod("cicUsersEditCheckPasswdString",
                    function(value, element, param) {
                        var isValidPwd = (/^[^<>;,"'&\\\/|+:= ]+$/.test(value));
                        return (value.length == 0 || isValidPwd);
                    },
                    validPassword
                );
            }

            /**
             * Initialize the view.
             */
            this.init = function () {
                loginTitle = document.title;
                $(TITLE).text(loginTitle);
                formStateView.init({form: FORM});
                initForm();
                $(BUTTON).on('click',function(ev) {
                    onOKButtonClick();
                });
                this.resume();
            };

            /**
             * Returning to this page after being away.
             */
            this.resume = function() {
                var username = presenter.getUsername();
                if (!username) {
                    // We're not in an initial password change sequence.
                    // Probably they restored a bookmark or hit Back or
                    // some such.  This will send them to their requested or
                    // default page (if they logged in) or the login page
                    // (if they didn't).
                    onInitialPasswordSuccess();
                    return;
                }
                $(SPINNER).hide();
                $(PASSWORD_CHANGE_STATUS).hide();
                $(BUTTON).removeAttr(DISABLED);
                $(USER).val(presenter.getUsername());
                $(PASSWORD1).val('').focus();
                $(PASSWORD2).val('');
                document.title = loginTitle;
            };

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

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

        }

        return new InitialPasswordView();
    }());
    return InitialPasswordView;
});
