/**
 * @ngdoc function
 * @name domainManagerApp.controller:AboutCtrl
 * @description
 * # AboutCtrl
 * Controller of the domainManagerApp
 */

angular.module('goApp.background', ['famous.angular', 'goApp.data'])
  .controller('BackgroundController',['$scope', '$rootScope', '$famous', '$timeline', 'Data', '$timeout', function ($scope,  $rootScope, $famous, $timeline, Data, $timeout) {

    'use strict';

    // Functions

    $scope.loadBackgroundData = function() {
      $scope.videos = Data.getBackgrounds();
      $rootScope.$on('data:loaded', function(data) {
        if(!$scope.$$phase) {
          $scope.$apply(function(){
            $scope.videos = Data.getBackgrounds();
            $scope.preload();
          });
        } else {
          $scope.videos = Data.getBackgrounds();
          $scope.preload();
        }
      });
    };

    $scope.preload = function() {
      $scope.current_video = $scope.videos[$scope.randomIntFromInterval(0,$scope.videos.length)];
      if($scope.current_video == undefined){
        $scope.current_video = "content/videos/bg_1.mov"
      }
      var preload = new createjs.LoadQueue();
      console.log("> Preloading video: " + $scope.current_video);
      function handleFileComplete(event) {
          console.log("> Preload Complete");
          $scope.startBackgroundVideo();
          $timeout(function(){
            $rootScope.$broadcast('background:loaded');
          },1500);
      }
      preload.addEventListener("fileload", handleFileComplete);
      // for (var i = 0; i < $scope.videos.length; i++) {
      //     preload.loadFile($scope.videos[i]);
      // }
      preload.loadFile($scope.current_video);

    };

    $scope.randomIntFromInterval = function(min,max) {
        return Math.floor(Math.random()*(max-min+1)+min);
    };

    $scope.startBackgroundVideo = function() {
      console.log("> Playing background video");
      var video = new VideoSurface({
          size: [undefined, undefined],
          autoplay: true,
          src: $scope.current_video,
          classes: ['bg_video'],
          properties: {
              zIndex: 1,
          }
      });
      video.setAttributes({ loop: '' });
      var videoModifier = new Modifier();
      videoModifier.transformFrom(function(){
          //transform: Transform.translate(0, 0, 0);
          Transform.translate(0, 0, 0);
      });
      $scope.backgroundView.add(videoModifier).add(video);
    };

    // Start Background Controller

    var View = $famous['famous/core/View'];
    var Modifier = $famous['famous/core/Modifier'];
    var Surface = $famous['famous/core/Surface'];
    var Transform = $famous['famous/core/Transform'];
    var VideoSurface = $famous['famous/surfaces/VideoSurface'];
    $scope.backgroundView = new View();

    $scope.loadBackgroundData();

  }]);
