var mod = angular.module('bananaraceApp.controllers');


mod.controller('PouleViewerCtrl', ['$scope', '$timeout', '$location', '$cookies', '$routeParams', 'ViewerService', 'PouleService', '$interval',
    function($scope, $timeout, $location, $cookies, $routeParams, ViewerService, PouleService, $interval) {

        //store all the teams
        $scope.teamsInPoule = [];

        $scope.currentTier = $routeParams.tier;
        $scope.currentPoule = $routeParams.poule;

				//init cycletime


				$scope.setCyclingPouleView = function(currentCyclingSetting) {
					// console.log('SETTING CYCLING POULE VIEW'+currentCyclingSetting);
					$cookies.put('cyclingpouleview', currentCyclingSetting);
					// console.log('SETCYCLINGPOULE VIEW after set:'+$cookies.get('cyclingpouleview'));
					if(currentCyclingSetting===false) {
						// console.log('SETCYCLINGPOULE VIEW cancelling the timer');
						$timeout.cancel($scope.cyclingTimer);
					} else if(currentCyclingSetting === true){
						// console.log('SETCYCLINGPOULE VIEW setting the timer! ');
						setCyclingTimer($scope.nextViewerLink, $scope.cycletime);
					} else {
						// console.log('wtf mate');
					}
				};

				$scope.getCyclingPouleView = function() {
					if($cookies.get('cyclingpouleview')!=undefined) {
						// console.log('defined in bookies, returning: '+$cookies.get('cyclingpouleview'));
						return $cookies.get('cyclingpouleview')=='true';
					} else {
						// console.log('returning default: false');
						return false;
					}
				};

				$scope.getCyclingPouleTime = function() {
					if($cookies.get('cyclingpouletime')!=undefined) {
						return parseInt($cookies.get('cyclingpouletime'));
					} else {
						return 10;
					}
				};

				$scope.cyclingPouleTimeChanged = function(cycletime) {
					//set the time in the service
					$cookies.put('cyclingpouletime',cycletime);
					// console.log('poule time changed');
					//reset the cycle timer if necessary
					if($scope.getCyclingPouleView()) {
						$timeout.cancel($scope.cyclingTimer);
						setCyclingTimer($scope.nextViewerLink, cycletime);
					}
				};

        $scope.refreshTeamsForPoule = function() {
            var idchampionship = $routeParams.idchampionship;
            var tier = $routeParams.tier;
            var poule = $routeParams.poule;
            ViewerService.getTeamsForPoule(idchampionship, tier, poule).
            success(function(data, status, headers, config) {
                // console.log('getTeamsForPoule successful...');
                // console.log(data);
                if (data['ok'] == true) {
                    $scope.teamsInPoule = data.teams;
                } else {
                    console.log('call returned but wasnt ok: ' + data.error);
                }
            }).
            error(function(data, status, headers, config) {
                console.log('getTeamsForPoule failed...');
            });
        };

				var setCyclingTimer = function(link, time) {
					if(time == undefined) {
						console.log('cant set a timer without time you fool...'+time);
						return;
					}
					// console.log('-- SET CYCLING TIMER ('+time+') enabling cycle timer'+time+' '+(time*1000)+link);
					$scope.cyclingTimer = $timeout(function() {
						$interval.cancel($scope.refreshTimer);
						//go to next page
						// $location.url('http://google.com');
						$location.url(link);
					}, (time*1000));
				};

				$scope.setNextPouleLink = function() {
					//load all poules of the current tier
					PouleService.getPoules($routeParams.idchampionship).
					success(function(data, status, headers, config) {
							// console.log('getTeamsForPoule successful...');
							console.log(data);
							var tier = $routeParams.tier;
							var currentPoule = $routeParams.poule;
							var idchampionship = $routeParams.idchampionship;
							if (data['ok'] == true) {
									//get all the poules of this tier in one array
									var poules = [];
									for (var i = 0; i < data.poules.length; i++) {
										if(data.poules[i].tier == tier)
											poules.push(data.poules[i].poule);
									}
									//set up the next poule to be loaded
									poules.sort();
									//look up the currentpoule
									var nextIndex = -1;
									if(poules.indexOf(currentPoule) == poules.length-1) {
										nextIndex = 0;
									} else {
										nextIndex=poules.indexOf(currentPoule)+1;
									}
									//set the link
									$scope.nextViewerLink = "/viewer/championship/"+idchampionship+"/poule/"+tier+"/"+poules[nextIndex]+"/overview";
									//                             /viewer/championship/16/poule/1/1/overview
									//http://localhost/bananarace/#/viewer/championship/16/poule/1/1/overview

									// console.log('built next viewer link:'+$scope.nextViewerLink);
									if($scope.getCyclingPouleView()) {
										console.log('jus fetched data, gonna enable cycle timer!');
										setCyclingTimer($scope.nextViewerLink, $scope.cycletime);
									}

							} else {
									console.log('call returned but wasnt ok: ' + data.error);
							}
					})
				};



				$scope.average = function(times) {
					console.log('average got called: '+times);

					var sum = 0;
					for (var i = 0; i < times.length; i++) {
						console.log(times[i]);
						sum+=times[i];
					}
					sum/=times.length;
					return sum;
				};

				$scope.getAverageOfBestOfTwo = function(races) {
					// console.log('getting avg of best of two');
					// console.log(races);
					//collect sum laptimes
					var sumlaptimes = [];
					for (var i = 0; i < races.length; i++) {
						if(races[i].sumlaptime!=undefined)
							sumlaptimes.push(races[i].sumlaptime);
					}
					//sort the avglaptimes
					sumlaptimes.sort();
					sumlaptimes.reverse();

					//cut off everything but two
					var removeThisMany = 2;
					sumlaptimes.splice(removeThisMany, sumlaptimes.length-removeThisMany);

					// console.log(sumlaptimes);

					if(sumlaptimes.length==2) {
						return (parseFloat(sumlaptimes[0])+parseFloat(sumlaptimes[1]))/2;
					} else {
						return undefined;
					}
				};

				$scope.bestOfTwo = function(race, races) {
					//can't do anything if you don't give me the arrrrrs
					if(races.length<2)
						return 'unknown';
					if(race == null)
						return 'unknown';
					if(races == null)
						return 'unknown';


					//collect sum laptimes
					var sumlaptimes = [];
					for (var i = 0; i < races.length; i++) {
						sumlaptimes.push(races[i].sumlaptime);
					}
					//sort the avglaptimes
					sumlaptimes.sort();
					sumlaptimes.reverse();
					//cut off everything but two
					var removeThisMany = 2;
					sumlaptimes.splice(removeThisMany, sumlaptimes.length-removeThisMany);
					var laptimesok =  sumlaptimes.indexOf(race.sumlaptime)!=-1;

					//are there enough laptimes present?
					var oklaptimescount = 0;
					for (var i = 0; i < races.length; i++) {
						if(races[i].laptimes.length>0)
							oklaptimescount++;
					}
					var laptimesarethere = oklaptimescount>1;

					if(laptimesarethere && laptimesok) {
						return 'best';
					}
					if(!laptimesarethere) {
						return 'unknown';
					}
					return 'notthebest';
				};

				//cycle settings
				$scope.currentCyclingSetting = $scope.getCyclingPouleView();
				$scope.cycletime = $scope.getCyclingPouleTime();

				//refresh data: initial init
				$scope.refreshTeamsForPoule();

				//do times things: keep refreshing
				//TODO this refresh shouldn't just reset the variable, it should overwrite team's times cleverly...
        $scope.refreshTimer = $interval($scope.refreshTeamsForPoule, 2000);
        // Cancel timer on destroying controller
        $scope.$on('$destroy', function() {
            $interval.cancel($scope.refreshTimer);
        });
				$scope.$on('$destroy', function() {
            $timeout.cancel($scope.cyclingTimer);
        });

				$scope.setNextPouleLink();



    }


]);
