Source: components/home.js

define('application/components/home', [
    'application/components/uibuilder',
    'application/managers/api',
    'antie/runtimecontext',
    'rofl/widgets/label',
    'rofl/lib/l10n',
    'rofl/widgets/container',
    'antie/widgets/verticallist',
    'rofl/lib/utils',
    'application/managers/genre',
    'application/models/uibuilder/filteredResult',
    'application/widgets/movies/grid',
    'rofl/lib/promise',
    'application/widgets/infoblock',
    'rofl/events/keyevent',
    'antie/storageprovider',
    'application/widgets/uibuilder/filter'
], function (
    UIBuilder,
    ApiManager,
    RuntimeContext,
    Label,
    L10N,
    Container,
    VerticalList,
    Utils,
    GenreManager,
    FilteredResult,
    Grid,
    Promise,
    InfoBlock,
    KeyEvent,
    StorageProvider
) {
    'use strict';

    var api = ApiManager.getKPNAPI(),
        application = RuntimeContext.getCurrentApplication(),
        device = application.getDevice(),
        storage = device.getStorage(StorageProvider.STORAGE_TYPE_SESSION, 'storage'),
        layout = application.getLayout(),
        l10n = L10N.getInstance(),
        filterTypes = {
            SORT: 'sort',
            FILTER: 'filter'
        },
        infoblockConfig = {
            id: 'back-on-top-block',
            text: l10n.get('infoblock'),
            classname: ['icon', 'icon-back-v2'],
            position: 'right'
        },
        STORAGE_ITEMS = {
            parental: 'parental'
        },
        topPosition = layout.home.top;

    return UIBuilder.extend({

        /**
         * Initialises the component.
         */
        init: function init () {
            this.pageId = 'home';
            init.base.call(this);
        },

        /**
         * Builds the component.
         *
         * @private
         */
        _build: function _build () {
            _build.base.call(this);

            this._buildPageContainer();
            this._buildHeader();
            this._buildTitle({
                label: {text: l10n.get('home.title'), classNames: ['top-title']}
            });
            this._buildInfoBlock();
        },

        /**
         * Builds the page container.
         *
         * @private
         */
        _buildPageContainer: function () {
            var pageContainer = this._pageContainer = new VerticalList();

            this.appendChildWidget(pageContainer);
        },

        /**
         * Builds the header container.
         *
         * @private
         */
        _buildHeader: function () {
            var header = this._header = new Container();

            header.addClass('header');
            this._pageContainer.appendChildWidget(header);
        },

        /**
         * Builds the infoblock.
         *
         * @private
         */
        _buildInfoBlock: function () {
            var infoblock = this._infoblock = new InfoBlock(infoblockConfig);

            infoblock.addClass('info-block');

            this.appendChildWidget(infoblock);
        },

        /**
         * Builds the no results message.
         *
         * @private
         */
        _showNoResultsMessage: function () {
            var noResultsLabel = this._noResultsLabel = new Label({
                text: l10n.get('home.noresults'),
                classNames: ['noresults']
            });

            this.addClass('empty-result');
            this._widgetList.removeChildWidgets();
            this._widgetList.appendChildWidget(noResultsLabel);
        },

        /**
         * BeforeShow event.
         *
         * @param {Object} e - The event data.
         */
        onBeforeShow: function (e) {
            var activeRowIndex,
                isParentalActive,
                eventArgs = e.args;

            application.showLoader();
            if (!e.fromBack) {
                this._resetPage();
                this._branding.hide({
                    skipAnim: true
                });
                this._infoblock.hide({skipAnim: true});

                if (eventArgs && Utils.isFunction(eventArgs.callback)) {
                    eventArgs.callback();
                }
            } else {
                application.hideLoader();
                this.alignCarouselsToLastIndex();
                activeRowIndex = this._widgetList && this._widgetList.getActiveChildWidgetIndex();
                this._widgetList.focus();
                isParentalActive = storage.getItem(STORAGE_ITEMS.parental);

                if (activeRowIndex > 1) {
                    this._infoblock.show();
                } else {
                    this._infoblock.hide({skipAnim: true});
                }

                if (!this._assetsUnlocked && !isParentalActive) {
                    this._unlockAssets();
                }
            }

            this._updateProgressbars();
        },

        /**
         * Loads the data.
         *
         * @param {Object} params - The parameters.
         * @private
         */
        _loadData: function loadMoviesData (params) {
            var defaultParams = {
                    page: application.getConfiguration().PAGES.HOME
                },
                customParams = params || {},
                allParams = Utils.extend(defaultParams, customParams);

            api.read('uibuilder/page', {
                params: allParams
            }).then(Utils.bind(function (sectionsPage) {
                var promises = [];

                promises.push(sectionsPage.prepareHero());
                promises.push(sectionsPage.prepareCarousels());

                Promise.all(promises)
                    .then(Utils.bind(this._onDataReady, this));

            }, this));
        },

        /**
         * Loads the filtered data.
         *
         * @private
         */
        _loadFilteredData: function loadFilteredData () {
            var firstLoadTo = application.getConfiguration().series.firstLoadTo;

            if (Object.keys(this._getActiveFilters()).length < 1) {
                this._resetPage();
                return;
            }

            this._previousActiveRowNumber = null;
            this._buildGrid();
            this._getFilteredData(firstLoadTo)
                .then(Utils.bind(this._onDataReady, this));
        },

        /**
         * Returns the filtered data.
         *
         * @param {number} [firstLoadTo] - The first number to load if not paginating.
         *
         * @returns {Promise} - Returns the filtered data promise.
         * @private
         */
        _getFilteredData: function (firstLoadTo) {
            var selectedFilter = this._getActiveFilters()[filterTypes.FILTER] ? this._getActiveFilters()[filterTypes.FILTER].value : null,
                selectedSort = this._getActiveFilters()[filterTypes.SORT] ? this._getActiveFilters()[filterTypes.SORT].value : null,
                newPaginationIndex = this._lastPaginationIndex + application.getConfiguration().series.followingLoads,
                filter,
                order,
                sort,
                options,
                pagination;

            sort = selectedSort ? '&sortOrder=' + selectedSort.sortOrder : '';
            order = selectedSort ? '&orderBy=' + selectedSort.orderBy : '';

            if (firstLoadTo) {
                pagination = '&from=0&to=' + firstLoadTo;
                newPaginationIndex = firstLoadTo;
            } else {
                pagination = '&from=' + this._lastPaginationIndex + '&to=' + newPaginationIndex;
            }

            this._lastPaginationIndex = newPaginationIndex;

            filter = selectedFilter ? '&filter_excludedGenres=' + this._getActiveFilters()[filterTypes.FILTER].value : '';
            options = {
                uri: '/TRAY/SEARCH/VOD/' +
                    '?filter_contentType=GROUP_OF_BUNDLES' +
                    '&filter_contentSubtype=SERIES' +
                    '&filter_quality=hd' +
                    '&dfilter_packages=matchSubscription' +
                    '&filter_technicalPackages=10078,10081,10129,10132,10159,10162,10228,10231,10252,10255,10258,10261'
                    + order + sort + filter + pagination
            };

            return new FilteredResult(options).prepare();
        },

        /**
         * Lazy loading data fetch.
         *
         * @private
         */
        _loadMoreFilteredData: function _loadMoreFilteredData () {
            if (!this._loadInProgress) {
                this._loadInProgress = true;
                this._getFilteredData()
                    .then(Utils.bind(function (data) {
                        if (data._items) {
                            this._grid.appendData(data._items, false, false);
                        }

                        this._loadInProgress = false;
                    }, this));
            }
        },

        /**
         * Gets executed when the page data has loaded.
         *
         * @param {Array} pageSections - The sections to build.
         * @private
         */
        _onDataReady: function (pageSections) {
            var sections = this._parseSections(pageSections),
                homeLayout = layout.home,
                firstContentCarousel;

            topPosition = homeLayout.top;

            this.buildWidgets(sections);
            this.alignCarousels();

            firstContentCarousel = this._widgetList.getChildWidgetByIndex(0);

            this._addFilterWidget();
            this._buildClock();
            this._widgetList.focus();

            if (!this.heroFound) {
                topPosition = homeLayout.topNoHero;
                firstContentCarousel.focus();
            }

            this._widgetList.setStyleTo('top', topPosition + 'px');
            application.hideLoader();
        },

        /**
         * Transforms the sections.
         *
         * @param {Array} pageSections - The sections to transform.
         * @returns {Object} - Returns an object with a collection of hero slider items and carousels.
         */
        _parseSections: function (pageSections) {
            var hero = pageSections[0],
                carousels = pageSections[1];

            return {
                hero: hero,
                carousels: carousels
            };
        },

        /**
         * Builds the widgets and appends them to the component.
         *
         * @param {Object} pageSections - The sections that contains collections of widgets.
         * @param {Object} [sectionParams] - Specific params to use for the widgets. i.e. layouts.
         */
        buildWidgets: function (pageSections, sectionParams) {
            var hero = pageSections.hero,
                carousels = pageSections.carousels,
                sections = [];

            if (hero && hero.getItems().length) {
                sections = sections.concat(hero);
            }

            if (carousels.length) {
                sections = sections.concat(carousels);
            }

            this.heroFound = false;

            Utils.each(sections, function (section) {

                this.buildWidget(section, sectionParams);
            }, this);

            if (!this.heroFound) {
                this._branding.hide({
                    skipAnim: true
                });
                this.addClass('no-hero-item');
                this._list.getChildWidgetByIndex(0).focus();
            } else {
                this._branding.show({
                    duration: 300
                });
                if (this.hasClass('no-hero-item')) {
                    this.removeClass('no-hero-item');
                }
            }
        },

        /**
         * Builds the grid.
         *
         * @private
         */
        _buildGrid: function () {
            var opts = {
                loadmoreCallback: Utils.bind(this._loadMoreFilteredData, this)
            };

            this._grid = new Grid(opts);
        },

        /**
         * Unlock the assets.
         *
         * @private
         */
        _unlockAssets: function () {
            var rows = this._widgetList.getChildWidgets(),
                assets;

            this._assetsUnlocked = true;
            Utils.each(rows, function (row) {
                if (row.getCarousel) {
                    assets = row.getCarousel().getChildWidgets();

                    Utils.each(assets, function (asset) {
                        if (asset.hasClass('asset')) {
                            asset.unlock();
                        }
                    });
                }
            });

            if (this._grid) {
                Utils.each(this._grid.getList().getChildWidgets(), function (row) {

                    Utils.each(row.getChildWidgets(), function (asset) {
                        if (asset.hasClass('asset')) {
                            asset.unlock();
                        }
                    });
                });
            }
        },

        /**
         * Select event.
         *
         * @param {Object} e - The event data.
         * @private
         */
        _onSelect: function (e) {
            var eventTarget = e.target,
                contentItem,
                selectAction = Utils.bind(function () {
                    contentItem = eventTarget.getDataItem().item;

                    if (eventTarget.playOnSelect()) {
                        if (contentItem.canPlay()) {
                            this._routeToPlayer({
                                data: contentItem,
                                type: 'VOD_MOVIE',
                                callingPage: this.pageId
                            }, 'vodplayer');
                        }
                    } else if (eventTarget.hasClass('asset')) {
                        this._routeToDetails({
                            data: contentItem
                        });
                    }
                }, this),
                sliderItem;

            switch (eventTarget.id) {
                case 'back-on-top-block':
                    this._onBack();
                    return;

                // no default
            }

            if (eventTarget.hasClass('watchall')) {
                this.goToWatchAll(e.target.getDataItem());
                return;
            }

            if (eventTarget.hasClass('slider-item') || (eventTarget.hasClass('epg') || eventTarget.hasClass('vod'))) {
                sliderItem = e.target.getDataItem();
                contentItem = sliderItem.item || sliderItem.getItem();

                selectAction = Utils.bind(this._routeToDetails, this, {
                    data: contentItem
                });

                if (contentItem.isLocked()) {
                    application.route('parentalpin', {
                        successCallback: Utils.bind(function () {
                            selectAction();
                            this._unlockAssets();
                        }, this)
                    });
                } else {
                    selectAction();
                }
            } else if (e.target.hasClass('pointer-button-big')) {

                if (e.target.hasClass('left-pointer')) {
                    e.target.parentWidget.getCarousel().alignPrevious();
                } else if (e.target.hasClass('right-pointer')) {
                    e.target.parentWidget.getCarousel().alignNext();
                }
            } else if (!e.target.isLocked()) {
                selectAction();
            } else {
                application.route('parentalpin', {
                    successCallback: Utils.bind(function () {
                        selectAction();
                        this._unlockAssets();
                    }, this)
                });
            }
        },

        /**
         * Builds genre filters. Home page doesn't include filters.
         *
         * @private
         */
        _buildGenreFilters: function () {},

        /**
         * Selected item change event.
         *
         * @param {Object} e - The event data.
         * @private
         */
        _onSelectedItemChange: function (e) {
            var activeRowNumber,
                itemsLength,
                target = e.target;

            if (target === this._widgetList && !this._grid) {

                this._scroll(e);
                activeRowNumber = e.index + 1;

                if (activeRowNumber > 1) {
                    this._infoblock.show();
                    this._branding.hide({
                        skipAnim: true
                    });
                } else {
                    this._infoblock.hide();

                    if (this._hero) {
                        this._branding.show({
                            skipAnim: false
                        });
                    }
                }

            } else if (this._grid) {
                activeRowNumber = this._grid.getActiveChildIndex() + 1;

                if (activeRowNumber > 1) {
                    this._infoblock.show();
                } else {
                    this._infoblock.hide();
                }

                if (this._grid.getDataItem()) {
                    itemsLength = this._grid.getDataItem().items.length;

                    this._scroll(e, true);

                    if (!this._previousActiveRowNumber || activeRowNumber > this._previousActiveRowNumber && itemsLength < this._totalCount) {
                        this._grid.checkLoadMore();
                        this._previousActiveRowNumber = activeRowNumber;
                    }
                }
            }
        },

        /**
         * Back event.
         *
         * @private
         */
        _onBack: function () {
            var activeRowNumber,
                topCarousel;

            if (this._grid) {
                activeRowNumber = this._grid.getActiveChildIndex() + 1;
            } else {
                activeRowNumber = this._widgetList._selectedIndex + 1;
            }

            if (activeRowNumber !== 1) {
                if (this._grid) {
                    this._grid.alignToFirstItem();
                } else {
                    this._widgetList.setActiveChildIndex(0);

                    topCarousel = this._widgetList.getChildWidgetByIndex(0).getCarousel();
                    topCarousel.alignToIndex(0);
                    topCarousel.setActiveChildIndex(0);
                }

            } else {
                application.focusMenu('main');
            }
        },

        /**
         * Reset the page to initial view.
         *
         * @private
         */
        _resetPage: function () {
            this.removeAll();
            this.removeClass('empty-result');
            this._loadData();
            this._grid = null;
        },

        /**
         * Scrolls the page.
         *
         * @param {Object} e - The selected item change event data.
         * @param {boolean} donotAnim - Do not animate.
         * @param {boolean} [reset] - True if the alignment should reset.
         * @private
         */
        _scroll: function (e, donotAnim, reset) {
            if (!e.item.outputElement) {
                return;
            }

            if (!this._grid || this._grid.getActiveChildIndex() > 0) {
                this._branding.hide({
                    duration: 300
                });
            }

            // Skip align at last carousel, this way we don't leave a gap at the end of the screen.
            if (this._widgetList.getIndexOfChildWidget(e.item) >= 0) {
                this._align(e.item, donotAnim, reset, e.index);
            }
        },

        /**
         * Aligns the widgetlist to the item.
         *
         * @param {Object} item - The item.
         * @param {boolean} doNotAnim - Prevent animation.
         * @param {boolean} [reset] - True if the alignment should reset.
         * @private
         */
        _align: function (item, doNotAnim, reset, index) {
            var listElement = this._widgetList.outputElement,
                listTop = listElement.getBoundingClientRect().top,
                left = 0,
                dimensions,
                difference,
                newTop,
                homeLayout = layout.home,
                marginTop = homeLayout.marginTop;

            dimensions = item.outputElement.getBoundingClientRect();

            if (index > 1 || (index && !this.heroFound)) {
                dimensions = this._widgetList.getChildWidgetByIndex(index - 1).outputElement.getBoundingClientRect();
            }

            difference = dimensions.top - marginTop;

            if (difference > 0) {
                newTop = listTop - difference;
            } else {
                newTop = listTop + -difference;
            }

            if (newTop > 0 || reset) {
                newTop = topPosition;
            }

            device.moveElementTo({
                el: listElement,
                duration: 300,
                fps: 60,
                easing: 'easeInOut',
                skipAnim: !!doNotAnim,
                to: {
                    top: newTop,
                    left: left
                }
            });

        }
    });
});