/**
 * @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,3)];
      console.log("> Preloading video: " + $scope.current_video);
      var preload = new createjs.LoadQueue();
      preload.addEventListener("complete", handleFileComplete);
      // for (var i = 0; i < $scope.videos.length; i++) {
      //     preload.loadFile($scope.videos[i]);
      // }
      preload.loadFile($scope.current_video);
      function handleFileComplete(event) {
          console.log("> Preload Complete");
          $scope.startBackgroundVideo();
          $timeout(function(){
            $rootScope.$broadcast('background:loaded');
          },1000);
      }
    };

    $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();

  }]);