Source: components/init.js

define('application/components/init', [
    'rofl/widgets/component',
    'rofl/widgets/label',
    'antie/runtimecontext',
    'rofl/lib/promise',
    'application/managers/channel',
    'rofl/media/source',
    'rofl/devices/mediaplayer/mediaplayer',
    'application/managers/session',
    'rofl/lib/utils',
    'rofl/analytics/web/google',
    'application/managers/feature',
    'rofl/logging/graylog',
    'antie/storageprovider',
    'rofl/lib/l10n'
], function (
    Component,
    Label,
    RuntimeContext,
    Promise,
    ChannelManager,
    MediaSource,
    MediaPlayer,
    SessionManager,
    Utils,
    GoogleAnalytics,
    FeatureManager,
    Graylog,
    StorageProvider,
    L10N
) {
    'use strict';

    var device = RuntimeContext.getDevice(),
        application = RuntimeContext.getCurrentApplication(),
        splash = application.getConfiguration().videos.LOGO,
        maxSplashTime = application.getConfiguration().MAX_SPLASH_TIME,
        mediaPlayer = device.getMediaPlayer(),
        sessionManager = SessionManager.getInstance(),
        GA = GoogleAnalytics.getInstance(),
        graylog = Graylog.getInstance(),
        featureManager = FeatureManager.getInstance(),
        configuration = application.getConfiguration(),
        storage = device.getStorage(StorageProvider.STORAGE_TYPE_PERSISTENT, 'survey'),
        l10n = L10N.getInstance(),
        sd = new Date(configuration.surveyDate),
        surveyCookieName = 'survey' + sd.getDate() + (sd.getMonth() + 1) + sd.getFullYear();

    return Component.extend({

        /**
         * PlayerEvent.
         *
         * @param {Object} e - The event data.
         */
        onPlayerEvent: function (e) {
            if (e.type === MediaPlayer.EVENT.COMPLETE) {
                this._promise
                    .then(Utils.bind(this._onReady, this));

                clearTimeout(this._timeout);
            }
        },

        /**
         * BeforeHide event.
         */
        onBeforeHide: function () {
            mediaPlayer.removeEventCallback(this, this.onPlayerEvent);
        },

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

            mediaPlayer.addEventCallback(this, this.onPlayerEvent);
        },

        /**
         * BeforeShow event.
         */
        onBeforeShow: function () {
            if (featureManager.isBrandingEnabled()) {
                this._promise = this._prepare();

                // starts countdown
                this._timeout = setTimeout(Utils.bind(function () {

                    /**
                     * Stops loading video and waits until necessary user requests are finished,
                     * then routes to the app,
                     */
                    if (mediaPlayer.getState() !== MediaPlayer.STATE.EMPTY) {
                        mediaPlayer.stop();
                        mediaPlayer.reset();
                    }
                    this._promise.then(Utils.bind(function () {
                        this._onReady();
                    }, this));
                }, this), maxSplashTime);
            } else {

                if (sessionManager.isEntryConfirmed()) {
                    application.showLoader();

                    this._prepare()
                        .then(Utils.bind(this._onReady, this));
                } else {

                    application.route('preconnect');
                }
            }
        },

        /**
         * AfterShow event.
         */
        onAfterShow: function () {
            var mediaSource = new MediaSource(splash),
                value = ((application.getDate() - this._loadingTime) / 1000).toFixed(2);

            if (featureManager.isBrandingEnabled()) {
                mediaPlayer.setMediaSource(mediaSource);
                mediaSource.prepare()
                    .then(function () {

                        // Dirty hack to force playback from the 0 moment.
                        mediaPlayer.beginLivePlayback();
                    });
            } else {
                application.getRootWidget().addClass('branding-disabled');
                application.route('menu');
            }

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

        /**
         * Prepares any data needed for launch.
         *
         * @returns {Promise} - Promise resolving after preparation.
         * @private
         */
        _prepare: function () {
            var promises = [];

            // We already check if the user is logged in while loading, and prepare the user if needed.
            if (sessionManager.isLoggedIn()) {
                promises.push(this._prepareUser());
            }

            return Promise.all(promises);
        },

        /**
         * Gets executed when the initialisation has completed.
         *
         * @private
         */
        _onReady: function () {
            if (mediaPlayer.getState() !== MediaPlayer.STATE.EMPTY) {
                mediaPlayer.stop();
                mediaPlayer.reset();
            }

            if (sessionManager.isLoggedIn()) {

                if (application.getUser().isOutOfHome()) {
                    sessionManager.logout();
                    application.route('outofhome');
                    return;
                }
                application.getComponent('main')._historyStack = [];
                this.parentWidget.back();

                if (this._shouldShowSurvey()) {
                    this._showSurvey();
                } else {
                    application.route(configuration.routeAfterLogin);
                }
                graylog.onAppNotice('User logged in');

            } else {
                if (this._shouldShowSurvey()) {
                    this._showSurvey();
                } else {
                    application.route('landing');
                }
            }
        },

        /**
         * Check if we should show the survey.
         *
         * @returns {boolean} - Show survey.
         * @private
         */
        _shouldShowSurvey: function () {
            var cookie = storage.getItem(surveyCookieName),
                isSurveyShown = Utils.isUndefined(cookie) ? false : cookie;

            return isSurveyShown === false &&
                application.getDate() <= configuration.surveyDate &&
                featureManager.isSurveyEnabled();
        },

        /**
         * Show the survey.
         *
         * @private
         */
        _showSurvey: function () {
            var qrModalConfig = {
                title: l10n.get('survey.modal.title'),
                text: l10n.get('survey.modal.text'),
                imgUrl: 'src/assets/images/survey.png',
                buttons: [
                    {
                        label: l10n.get('survey.modal.close'),
                        class: 'confirm_button',
                        button: 'confirmbutton',
                        labelname: 'confirmButtonLabel'
                    }
                ],
                footer: l10n.get('survey.modal.footer'),
                callback: '',
                showGoBackButton: false
            };

            storage.setItem(surveyCookieName, true);

            if (sessionManager.isLoggedIn()) {
                qrModalConfig.callback = function () {
                    application.route(configuration.routeAfterLogin);

                    this.parentWidget.back();
                };
            } else {
                qrModalConfig.callback = function () {
                    application.route('landing');
                };
            }

            application.route('qrmodal', qrModalConfig);
        },

        /**
         * Prepares the user.
         *
         * @returns {Promise} - Promise resolving with the user.
         */
        _prepareUser: function () {

            // If the user fails to prepare, log out the user.
            return sessionManager.prepareUser()
                ['catch'](function () {
                return sessionManager.logout();
            });
        }
    });

});