/* global Keys, Player, App */
/* global APP_CONFIG */
/* global $, $$nav */

(function() {
    "use strict";

    App.modules.playerController = {
      errorBufTimer: null,

      addGeneralEvents: function () {
        Player.on('prepare', function() {
          App.loaderProc('');
          App.loader(true);
        });

        Player.on('bufferingBegin', function() {
          App.loaderProc(0);
          App.loader(true);
        });

        Player.on('bufferingEnd', function() {
          App.runText(true);

          clearTimeout(App.modules.playerController.errorBufTimer);

          App.loaderProc(100);
          App.loader(false, 'Player::bufferingEnd');
        });

        Player.on('buffering', function(proc) {
          App.loaderProc(proc);
        });

        Player.on('stop', function(proc) {
          App.runText(false);
        });
      },

      turnOnPlayerInterfaceSynchronization: function () {
        for (var eventName in PLAYER_INTERFACE_EVENTS) {
          Player.on(eventName, PLAYER_INTERFACE_EVENTS[eventName]);
        }
      },

      turnOffPlayerInterfaceSynchronization: function () {
        for (var eventName in PLAYER_INTERFACE_EVENTS) {
          Player.off(eventName, PLAYER_INTERFACE_EVENTS[eventName]);
        }
      },

      showPlayerInterface: function () {
        this.waitAndHidePlayerInterface(APP_CONFIG.VIDEO_PLAYER_AOUTHIDE_MS);

        if (this.isVisible) {
          return;
        }

        $('#appPlayer').fadeIn(function () {
          $$nav.save();
          $$nav.on($('#appPlayer'));
          $$nav.current($('#appPlayerPause'));
        });

        Keys.set('playerController');

        this.isVisible = true;
      },

      waitAndHidePlayerInterface: function (ms) {
        if (App.modules.interface.isVisible) {
          return;
        }

        clearTimeout(this.hidePlayerInterfaceTimer);

        this.hidePlayerInterfaceTimer = setTimeout(function () {
          App.modules.playerController.hidePlayerInterface();
        }, ms);
      },

      hidePlayerInterface: function () {
        if (!this.isVisible) {
          return false;
        }

        $('#appPlayer').fadeOut();

        this.emtyFocus();

        App.loader(false);

        this.isVisible = false;

        return true;
      },

      emtyFocus: function () {
        var $emptynav = $('#emptyNav');

        $emptynav.show();

        $$nav.current($emptynav);

        $emptynav.one('nav_blur', function () {
          $emptynav.hide();
        })
      },

      playEpisode: function(episode) {
        if (!App.modules.interface.isVisible) {
          return;
        }

        this.playSupportedFile(episode);
      },

      playSupportedFile: function (filmFiles)  {
        var supportedFormats = APP_CONFIG.VIDEO_SUPPORTED_FORMATS;

        for (var i=0; i<supportedFormats.length; i++) {
          var filmFormat = supportedFormats[i];
          var filmFile = filmFiles[filmFormat];

          if (filmFile) {
            App.modules.playerController.playUrl(filmFile.url);
            return true;
          }
        }

        App.error('video_unavailable_error');

        return false;
      },

      playUrl: function(url) {
        App.modules.interface.hideInterface();

        App.loader(true);

        App.modules.playerController.errorBufTimer = setTimeout(function() {
            Player.stop();
            App.modules.playerController.onVideoError();
        }, APP_CONFIG.VLIB_BUFFERING_TIMEOUT_ERROR_MS);

        App.modules.playerController.turnOnPlayerInterfaceSynchronization();

        Player.play({
            url: url,
            type: 'vod',
            onerror: function () {
              App.modules.playerController.onVideoError();
            }
        });
      },

      fastForward: function() {
        var duration = Player.videoInfo.duration;

        this.forward(Math.floor(duration * APP_CONFIG.VIDEO_PLAYER_REWIND_PERCENT / 100));
      },

      fastBackward: function() {
        var duration = Player.videoInfo.duration;

        this.backward(Math.floor(duration * APP_CONFIG.VIDEO_PLAYER_REWIND_PERCENT / 100));
      },

      forward: function(seconds) {
        if (!seconds) {
          seconds = 10;
        }

        var duration = Player.videoInfo.duration;
        var currentTime = Player.videoInfo.currentTime;

        Player.forward((currentTime + seconds) < duration ? seconds : (duration - currentTime));
      },

      backward: function(seconds) {
        if (!seconds) {
          seconds = 10;
        }

        var currentTime = Player.videoInfo.currentTime;

        Player.backward(currentTime > seconds ? seconds : currentTime);
      },

      onBufferingBegin: function() {
        App.dispatch(App.playerActions.setDuration(0));
      },

      onBufferingEnd: function() {
        var duration = Player.videoInfo.duration;

        App.dispatch(App.playerActions.setDuration(duration));

        if (Keys.view !== 'playerController') {
          App.modules.playerController.onVideoStart();
        }
      },

      onPlayTimeUpdate: function() {
        var currentTime = Player.videoInfo.currentTime;

        App.dispatch(App.playerActions.setPosition(currentTime))
      },

      onPause: function() {
        App.dispatch(App.playerActions.setPaused(true));
      },

      onResume: function() {
        App.dispatch(App.playerActions.setPaused(false));
      },

      onVideoStart: function() {
        App.modules.playerController.showPlayerInterface();
      },

      onVideoError: function() {
        App.loader(false);
        Keys.set('videoController');
        App.error('video_error', function(){
            App.modules.interface.showInterface();
            App.modules.playerController.hidePlayerInterface();
        });
        App.modules.playerController.turnOffPlayerInterfaceSynchronization();
      },

      onVideoStop: function() {
        Keys.set('videoController');
        App.modules.interface.showInterface();
        App.modules.playerController.turnOffPlayerInterfaceSynchronization();
        App.modules.playerController.hidePlayerInterface();
        App.modules.videoController.restore();
      }
    }

    var PLAYER_INTERFACE_EVENTS = {
      bufferingBegin: App.modules.playerController.onBufferingBegin,
      bufferingEnd: App.modules.playerController.onBufferingEnd,
      update: App.modules.playerController.onPlayTimeUpdate,
      pause: App.modules.playerController.onPause,
      resume: App.modules.playerController.onResume,
      stop: App.modules.playerController.onVideoStop,
    };

    App.modules.playerController.addGeneralEvents();
})();
