Source: components/login/pin.js

define('application/components/login/pin', [
    'rofl/widgets/component',
    'application/widgets/login/intro',
    'application/widgets/login/input',
    'rofl/lib/l10n',
    'rofl/lib/utils',
    'antie/runtimecontext',
    'application/managers/session',
    'rofl/events/keyevent',
    'rofl/analytics/web/google',
    'rofl/logging/graylog'
], function (
    Component,
    Intro,
    Input,
    L10N,
    Utils,
    RuntimeContext,
    SessionManager,
    KeyEvent,
    GoogleAnalytics,
    Graylog
) {
    'use strict';

    var l10n = L10N.getInstance(),
        application = RuntimeContext.getCurrentApplication(),
        sessionManager = SessionManager.getInstance(),
        GA = GoogleAnalytics.getInstance(),
        graylog = Graylog.getInstance(),
        inputConfig = {
            title: l10n.get('pin.title'),
            forgottenLoginButton: l10n.get('pin.buttons.forgotten'),
            backButton: l10n.get('pin.buttons.back'),
            loginButton: l10n.get('pin.buttons.login'),
            validationMsg: l10n.get('pin.validation.message'),
            inputField: {
                title: l10n.get('pin.inputfield.title'),
                type: Input.INPUT_FIELD_TYPES.PASSWORD,
                opts: {
                    placeholder: l10n.get('pin.inputfield.placeholder'),
                    maxLength: 4,
                    validateLength: true,
                    maskCharacter: '*'
                }
            }
        },
        confirmButton = {
            label: l10n.get('username.modalconfig.label'),
            class: 'confirm_button',
            button: 'confirmbutton',
            labelname: 'confirmButtonLabel'
        },
        modalconfig = {
            title: l10n.get('username.modalconfig.title'),
            text: l10n.get('username.modalconfig.text'),
            buttons: [
                confirmButton
            ]
        },
        wrongloginconfig = {
            title: l10n.get('username.wronginput.title'),
            text: l10n.get('username.wronginput.text'),
            buttons: [
                confirmButton
            ]
        },
        accountblockedconfig = {
            title: l10n.get('login.accountblockedconfig.title'),
            text: l10n.get('login.accountblockedconfig.text'),
            buttons: [
                confirmButton
            ]
        };

    return Component.extend({

        /**
         * Initialises the login component.
         */
        init: function init () {

            init.base.call(this, 'login');
            this.addClass(['login', 'pin']);
            this._build();

            this._onSelectBound = Utils.bind(this._onSelect, this);
            this._onKeyDownBound = Utils.bind(this._onKeyDown, this);
            this._onTextChangeBound = Utils.bind(this._onTextChange, this);
            this._onTextValidatedBound = Utils.bind(this._onTextValidated, this);
            this._onFocusBound = Utils.bind(this._onFocus, this);
        },

        /**
         * Builds the login component.
         *
         * @private
         */
        _build: function () {
            this._buildIntro();
            this._buildInput();
        },

        /**
         * Builds the intro widget.
         *
         * @private
         */
        _buildIntro: function () {
            var intro = this._intro = new Intro();

            this.appendChildWidget(intro);
        },

        /**
         * Builds the input widget.
         *
         * @private
         */
        _buildInput: function () {
            var input = this._input = new Input(inputConfig);

            this.appendChildWidget(input);
        },

        /**
         * BeforeRender event.
         */
        onBeforeRender: function () {
            this._loadingTime = application.getDate();
        },

        /**
         * BeforeShow event.
         *
         * @param {event} e - Passed event.
         */
        onBeforeShow: function (e) {
            var input = this._input,
                keyboard = input.getKeyboard().getKeyboard(),
                loginButton = input.getButton();

            GA.onPageView('login-pin');
            keyboard.setText('');
            this._username = e.args.username;
            input.focus();
            this._startPinPage = application.getDate();

            if (!this.getValue()) {
                input.getInputField().showCursorBlink();
                keyboard.setActiveChildKey('1');
                keyboard.focus();
            } else {
                input.getKeyboard().setActiveChildIndex(1);
                loginButton.focus();
                input.getInputField().stopCursorBlink();
            }
        },

        /**
         * AfterShow event.
         */
        onAfterShow: function () {
            var inputField = this._input.getInputField(),
                value = ((application.getDate() - this._loadingTime) / 1000).toFixed(2);

            this._setEventListeners();

            inputField.animateFocusBar();

            GA.onEvent('page', 'load', {
                eventLabel: 'pin',
                eventValue: value
            });
        },

        /**
         * BeforeHide event.
         */
        onBeforeHide: function () {
            var inputField = this._input.getInputField(),
                duration = ((application.getDate() - this._startPinPage) / 60000).toFixed(2);

            this._removeEventListeners();

            inputField.stopCursorBlink();
            inputField.stopFocusbarAnimation();
            GA.onEvent('page', 'time', {
                eventLabel: 'login-pin',
                eventValue: duration
            });
        },

        /**
         * Sets the event listeners.
         *
         * @private
         */
        _setEventListeners: function () {

            this.addEventListener('textchange', this._onTextChangeBound);
            this.addEventListener('select', this._onSelectBound);
            this.addEventListener('keydown', this._onKeyDownBound);
            this.addEventListener('textvalidated', this._onTextValidatedBound);
            this.addEventListener('focus', this._onFocusBound);
        },

        /**
         * Removes the event listeners.
         *
         * @private
         */
        _removeEventListeners: function () {

            this.removeEventListener('textchange', this._onTextChangeBound);
            this.removeEventListener('select', this._onSelectBound);
            this.removeEventListener('keydown', this._onKeyDownBound);
            this.removeEventListener('textvalidated', this._onTextValidatedBound);
            this.removeEventListener('focus', this._onFocusBound);
        },

        /**
         * Select event.
         *
         * @param {event} e - Passed select event.
         */
        _onSelect: function (e) {
            var target = e.target;

            switch (target.id) {
                case 'loginbtn':
                    this._onLogin();
                    break;
                case 'back':
                    this.parentWidget.back();
                    this.removeFocus();
                    break;
                case 'forgottenpin':
                    GA.onEvent('Action', 'ForgotCredentials');
                    application.route('modal', modalconfig);
                    break;
            }
        },

        /**
         * KeyDown event.
         *
         * @param {Object} e - The event data.
         * @private
         */
        _onKeyDown: function (e) {
            var keyboard = this._input.getKeyboard().getKeyboard(),
                currentText = keyboard.getText(),
                character;

            switch (e.keyCode) {
                case KeyEvent.VK_LEFT:
                case KeyEvent.VK_RIGHT:
                    e.stopPropagation();
                    e.preventDefault();
                    break;
                case KeyEvent.VK_BACK:
                    this.parentWidget.back();
                    break;
                case KeyEvent.VK_0:
                case KeyEvent.VK_1:
                case KeyEvent.VK_2:
                case KeyEvent.VK_3:
                case KeyEvent.VK_4:
                case KeyEvent.VK_5:
                case KeyEvent.VK_6:
                case KeyEvent.VK_7:
                case KeyEvent.VK_8:
                case KeyEvent.VK_9:
                    character = e.keyChar;
                    currentText += character;
                    keyboard.setText(currentText);
                    break;
            }
        },

        /**
         * Gets executed when the user wants to login.
         *
         * @private
         */
        _onLogin: function () {
            var validationMessage = this._input.getValidationMessage(),
                self = this;

            if (this.getValue().length === 4) {

                application.showLoader();
                sessionManager.login(this._username, this.getValue())
                    .then(function () {
                        if (application.getUser().isOutOfHome()) {
                            sessionManager.logout();
                            application.route('outofhome');
                            return;
                        }
                        sessionManager.setAccountNumber(self._username);
                        application.hideLoader();
                        application.route(application.getConfiguration().routeAfterFirstLogin);

                        GA.onEvent('Login', 'SuccesfullLogin');

                        graylog.onAppNotice('User logged in');
                    })
                    .catch(function (result) {
                        application.hideLoader();

                        GA.onEvent('Login', 'NotSuccesfullLogin');

                        if (Utils.getNested(result, 'errorDescription') === '401-3161') {
                            accountblockedconfig.errorCode = Utils.getNested(result, 'errorDescription');
                            accountblockedconfig.callback = Utils.bind(self.focus, self);
                            application.route('modal', accountblockedconfig);
                        } else {
                            wrongloginconfig.errorCode = Utils.getNested(result, 'errorDescription');
                            wrongloginconfig.text = l10n.get('username.wronginput.text', {attemps: Utils.getNested(result, 'resultObj', 'remainingAttempts')});
                            wrongloginconfig.callback = Utils.bind(self.focus, self);
                            application.route('modal', wrongloginconfig);
                        }

                    });
            } else {

                validationMessage.addClass('visible');
                this._input.getInputField().getFocusBar().addClass('redfocus');
            }
        },

        /**
         * Text Change event.
         *
         * @private
         */
        _onTextChange: function () {
            var validationMessage = this._input.getValidationMessage();

            validationMessage.removeClass('visible');
            this._input.getInputField().getFocusBar().removeClass('redfocus');
        },

        /**
         * Text validated event.
         *
         * @private
         */
        _onTextValidated: function () {
            this._input.getButton().focus();
            this._input.getKeyboard().setActiveChildIndex(1);
        },

        /**
         * Returns value of the input.
         *
         * @returns {string} - Value of the inupt.
         */
        getValue: function () {
            return this._input.getValue();
        },

        /**
         * Focus event.
         *
         * @param {Object} e - The event data.
         * @private
         */
        _onFocus: function (e) {

            if (e.target.hasClass('input-keys')) {
                this._input.getInputField().showCursorBlink();
            } else if (e.target.hasClass('kpn-button')) {
                this._input.getInputField().stopCursorBlink();
            }
        }
    });
});