/* global App, Keys */
/* global $, _, $$nav */

// var TEMP_URL = "https://www.w3schools.com/html/mov_bbb.mp4";

(function() {
    "use strict";
    var _inited;

    _.templateSettings.interpolate = /\{\{([\s\S]+?)\}\}/g;
    // шаблон списка
    var itemHtml = _.template(
      '<li '+
        'data-imdb="{{video_data.rate_imdb}}" '+
        'data-kino="{{video_data.rate_kinopoisk}}" '+
        'data-id="{{video_data.id}}" '+
        'data-name="{{video_data.name}}" '+
        'data-year="{{video_data.year}}" '+
        'data-genre_str="{{video_data.genre_str}}" '+
        'data-country="{{video_data.country}}" '+
        'data-lenght="{{video_data.lenght}}" '+
        'data-poster="http://rudny-online.kz{{video_data.poster}}" '+
        'class="video-item nav-item navigation-item" '+
        'style="background-image: url(\'http://rudny-online.kz{{video_data.poster}}\')"'+
      '/>'
    );

    var pageHtml = _.template('<li data-page="{{page}}" class="{{classname}} nav-but">{{text}}</li>');

    App.scenes.videolib = {
        itemHtml: itemHtml,
        toString: function() {
            return 'videolib';
        },
        bodyClassName: 'scene-videos',
        films: [],
        ratings: [],
        genre: null,

        init: function() {
          this.$el = $('.scene-videos-content');
          this.$genreselect = $('#genre-select');
          this.$ratingselect = $('#rating-select');
          this.$dateselect = $('#date-select');

          this.dates = {
            'last': App.t('video_last'),
            'year': App.t('video_year'),
          };

          this.date = 'last';
          this.page = 1;
          this.filterId = 'year';
          this.rating = 'kinopoisk';

          this.setSearchHeader('');
          this.loadRates();
          this.loadRateLine();
          this.loadGenresThenChooseRandom();
          this.loadYearLine(function () {
            App.modules.videoLines.selectFirstFilmInVideoLine();
          });

          App.scenes.videolib.$el.on('nav_focus', '.video-item', App.scenes.videolib.onVideoFocus);
          App.scenes.videolib.$el.on('nav_key:enter', '.video-item', App.scenes.videolib.onVideoClick);
          App.scenes.videolib.$el.on('nav_key:enter', '.date-but', App.scenes.videolib.openDateMenu);

          _inited = true;

          this.render();
        },

        render: function() {
          this.chooseDate(App.scenes.videolib.date);
        },

        show: function() {
          if (!_inited) {
              this.init();
          }

          this.$el.show();
  			  $('li[data-scene=video]').addClass('active');

          Keys.set('videoController');

          App.modules.videoLines.selectFirstFilmInVideoLine();
        },

        hide: function() {
          this.$el.hide();
		      $('li[data-scene=video]').removeClass('active');
        },

        setVideosFocusEvents: function() {
          this.$el.find('.video-item').on({
            'nav_focus': function() {
                var filmId = $(this).data('id');
                var film = App.scenes.videolib.getFilmById(filmId);

                App.dispatch(App.legendActions.setInfo('video_more_details'));

                App.modules.videoController.renderVideoInfo(film);

                App.scenes.videolib.focusedFilm = film;
            },

            'nav_blur': function() {
              App.dispatch(App.legendActions.setInfo(''));
            }
          });
        },

        getFilmById: function(filmId) {
          return this.films[filmId];
        },

        onVideoClick: function(e) {
          App.modules.videoController.navToButtonsBlock()
        },

        renderItems: function(items, params) {
            var html = [];

            for (var i = 0, len = items.length; i < len; i++) {
              html.push(itemHtml(items[i], params));
            }

            html.sort(function () {
              return Math.random() - 0.5;
            });

            this.getVideoLineByParams(params)
              .html(html.join(''));

            var isFirstLine = params.filter === 'year' && !params.genre;

            if (isFirstLine) {
              this.$el.find('#videos-list li').first().trigger('mouseenter');
            }
        },

        hideBeforeFilmsLoaded: function (loadingCount) {
          this.filmsLoading += loadingCount || 1;

          this.$el.find('#videos-list')
            .fadeOut(0);
        },

        showAfterFilmsLoaded: function (onComplate) {
          this.filmsLoading--;

          if (this.filmsLoading) {
            return;
          }

          this.$el.find('#videos-list')
            .fadeIn(400, onComplate);
        },

        getVideoLineByParams: function (params) {
          if (params.genre) {
            return $('#videos-list .by-genre .videos-line-inner');
          }

          if (
            params.filter === 'kinopoisk' ||
            params.filter === 'imdb'
          ) {
            return $('#videos-list .by-rating .videos-line-inner');
          }

          if (
            params.filter === 'last' ||
            params.filter === 'year'
          ) {
            return $('#videos-list .by-year .videos-line-inner');
          }

          return $('#videos-list .by-'+ params.filter +' .videos-line-inner');
        },

        renderPageSelector: function(page, pages) {
            var html = '';
            var neighbours = 2;
            var left_neighbour = page - neighbours;
            if (left_neighbour < 1)
                left_neighbour = 1;
            var right_neighbour = page + neighbours;
            if (right_neighbour > pages)
                right_neighbour = pages;
            if (page > 3)
            {
                html += pageHtml({page: 1, classname: 'nav-item', text: 1});
                html += pageHtml({page: (page - 1), classname: 'nav-item', text: '←'});
            }
            for (var i = left_neighbour; i <= right_neighbour; i++) {
                if (i != page)
                {
                    html += pageHtml({page: i, classname: 'nav-item', text: i});
                }
                else
                {
                    html += pageHtml({page: i, classname: 'current', text: i});
                }
            }
            if (page < (pages - 2))
            {
                html += pageHtml({page: (page + 1), classname: 'nav-item', text: '→'});
                html += pageHtml({page: pages, classname: 'nav-item', text: pages});
            }

            this.$el.find('#page-select li').off('nav_key:enter');
            if (pages == 1)
            {
                this.$el.find('#page-select')
                        .empty();
            }
            else
            {
                this.$el.find('#page-select')
                        .empty()
                        .html(html);
            }

            this.$el.find('#page-select li').on('nav_key:enter', function() {
                App.scenes.videolib.selectPage($(this).data('page'));
            });
        },

        chooseGenreId: function (genreId, options) {
          if (!genreId) {
            return;
          }

          if (!options) {
            options = {}
          }

          var selectFirstFilmCallback = !options.notSelectFirstFilm && function () {
            App.modules.videoLines.selectFirstFilmInVideoLine(2);
          }

          App.scenes.videolib.genre = genreId;
          App.scenes.videolib.loadGenreLine(selectFirstFilmCallback);

          App.dispatch(App.videoActions.setGenreId(genreId.toString()));
        },

        loadRates: function() {
          App.modules.videoController.api('method=filter', function(result) {
            $.each(result, function(index, value) {
              $.each(value, function(key, val) {
                if (val.indexOf('Рейтинг') < 0) {
                  return;
                }

                App.scenes.videolib.ratings.push({ value: key, label: val });
              });
            });

            App.dispatch(App.videoActions.setRatings(App.scenes.videolib.ratings));
            App.dispatch(App.videoActions.setRatingByValue(App.scenes.videolib.rating));
          });
        },

        openDateMenu: function (event) {
          var $dateselect = App.scenes.videolib.$dateselect;
          var $dateparent = $dateselect.find('ul');

          $dateselect.fadeIn(400, function() {
              // select current filter
              $dateparent.find('.filter-item[data-filter-id=' + App.scenes.videolib.filterId + ']').trigger('mouseenter').trigger('nav_focus');
          });

          $$nav.save();
          $$nav.on($dateselect);

          return false;
        },

        chooseDate: function (date) {
          if (!date) {
            return;
          }

          this.date = date;

          if (!this.date) {
            return;
          }

          if (!this.dates[date])
            return;

          $('.date-but').html($('[data-rating=' + date + ']').html());
        },

        loadGenresThenChooseRandom: function () {
          this.loadGenres(function () {
            App.scenes.videolib.chooseRandomGenre();
          })
        },

        chooseRating: function (rating) {
          if (!rating) {
            return;
          }

          this.rating = rating.value;

          if (!this.ratings) {
            return;
          }

          App.scenes.videolib.loadRateLine(function () {
            App.modules.videoLines.selectFirstFilmInVideoLine(1);
          });

          App.dispatch(App.videoActions.setRating(rating));
        },

        loadGenres: function(callback) {
          App.modules.videoController.api('method=genres', function(result) {
              App.dispatch(App.videoActions.setGenres(result));

              App.scenes.videolib.genres = result;

              if (callback) callback();
          });
        },

        chooseRandomGenre: function () {
          var genres = App.scenes.videolib.genres;
          var randomGenre = genres[_.random(0, genres.length - 1)].id;

          App.scenes.videolib.chooseGenreId(randomGenre, { notSelectFirstFilm: true });
        },

        loadFilms: function(params, callback) {
            App.progressStart();

            App.modules.videoController.api('method=films&page=' + params.page + '&genre=' + params.genre + '&filter=' + params.filter + '&search=' + this.searchText, function(result) {
                if (result[0].length > 0)
                {
                    var isFirstLine = params.filter === 'year' && !params.genre;

                    App.scenes.videolib.updateFilms(result[0]);
                    App.scenes.videolib.renderItems(result[0], params);
                    App.scenes.videolib.page = result[1].page;

                    if (isFirstLine) {
                      App.scenes.videolib.renderPageSelector(App.scenes.videolib.page, result[1].pages);
                    }

                    App.scenes.videolib.setVideosFocusEvents();
                    App.progressStop();
                } else {
                  // При загрузке первых лент может срендомиться жанр в котором нет видео (например 27)
                  // App.error('video_search_error', function() {
                  //     App.progressStop();
                  //     App.scenes.videolib.loadFilms();
                  // });
                }

                App.scenes.videolib.showAfterFilmsLoaded();

                if (callback) {
                  callback();
                }
            });
        },

        updateFilms: function (films) {
          $.each(films, function(index, film) {
            film.video_data.files = film.files;
            App.scenes.videolib.films[film.video_data.id] = film.video_data;
          });
        },

        selectPage: function(page, params) {
          if (!params) params = {};

          this.page = page;

          this.loadYearLine();
          this.loadRateLine();
          this.loadGenreLine();
        },

        loadYearLine: function (callback) {
          this.loadFilms({page: App.scenes.videolib.page, genre: 0, filter: 'year'}, callback);
          this.hideBeforeFilmsLoaded();
        },

        loadRateLine: function (callback) {
          this.loadFilms({page: App.scenes.videolib.page, genre: 0, filter: App.scenes.videolib.rating }, callback);
          this.hideBeforeFilmsLoaded();
        },

        loadGenreLine: function (callback) {
          this.loadFilms({page: App.scenes.videolib.page, genre: this.genre, filter: 'year'}, callback);
          this.hideBeforeFilmsLoaded();
        },

        setSearchHeader: function (text) {
          this.searchText = text;
          // TODO..
          $('.header .search-btn .value').html(text);
        },

        onVideoFocus: function (event) {
          App.modules.videoLines.autoScrollVertical(event);
        },

        closeOpenedPopup: function () {
          var $openedPopup = $('.popup:visible');

          if (!$openedPopup.length) {
            return false;
          }

          $openedPopup.fadeOut(400);
          $$nav.restore();

          return true;
        },

        back: function () {
          if (this.closeOpenedPopup()) {
            return;
          } else if (App.modules.videoController.back()) {
            return;
          } else {
            App.back();
          }
        }
    }
})();
