angular.module('bananaraceApp.controllers').controller('RaceCtrl', ['$scope', '$routeParams', 'RaceService', function($scope, $routeParams, RaceService) {
	//fetch all drives for the current race
	var drives = [];
  //contains a row for each drive/lap -> sorted on drivenr
  $scope.drivesExpanded = null;

	//set route params in scope variables
	$scope.currentChampionship = $routeParams.idchampionship;
	$scope.currentTier = $routeParams.tier;
	$scope.currentPoule = $routeParams.poule;
	$scope.currentRace = $routeParams.idrace;

	//possible lapamounts
	$scope.lapamounts = [1,2,3,4,5];
	//initial selection
	$scope.selectedLapamount = 2;

	//start of the lap, if necessary
	$scope.newMeasurementStarttime = new Date();

	//set the starting values for the relative start applet
	$scope.relativeRaceStartAddMinutes = 0;
	$scope.relativeRaceStartAddSeconds = 0;
	$scope.relativeRaceTime = new Date();
	$scope.rightnow = new Date();
	$scope.relativeRaceStart = $scope.rightnow;

	$scope.measurementValidityChanged = function(measurement) {
		console.log('measurement changed: '+measurement.valid);
		RaceService.updateMeasurement(measurement).
		success(function(data, status, headers, config) {
			console.log('updateMeasurement successful...');
			if(data['ok']==true) {
			} else {
			}
		}).
		error(function(data, status, headers, config) {
			console.log('updateMeasurement failed...');
		});;
	};

	$scope.relativeTimestampChanged = function() {
		var start = $scope.relativeRaceStart;
		var plusMinutes = $scope.relativeRaceStartAddMinutes;
		var plusSeconds = $scope.relativeRaceStartAddSeconds;

		console.log('plus seconds: '+plusSeconds);

		//using moments to calculate offsets and relative shit
		var newMoment = moment(start);
		newMoment.add(plusMinutes, 'minutes').add(plusSeconds, 'seconds');

		//set it!
		$scope.relativeRaceTime = newMoment;

		console.log('new relative time: '+newMoment);

	};

	$scope.setSelectedLapamount = function(amount) {
		$scope.selectedLapamount = amount;
	};

	$scope.refreshDrives = function() {
		console.log('doing refreshRaces');
		RaceService.getDrives($scope.currentRace).
		success(function(data, status, headers, config) {
			console.log('refreshDrives successful...');
			console.log(data);
			if(data['ok']==true) {
				$scope.drives = data.drives;

        //set the expanded version
        $scope.drivesExpanded = [];
        for(var drivei = 0; drivei<data.drives.length; drivei++) {
          var laps = data.drives[drivei].laps;
          for(var i = 0; i<laps; i++) {
            var lapdrive = {
              lap: (i+1),
              drivenr:data.drives[drivei].drivenr,
              drivername:data.drives[drivei].drivername
            };
            $scope.drivesExpanded.push(lapdrive);
          }
        }
			} else {
			}
		}).
		error(function(data, status, headers, config) {
			console.log('refreshDrives failed...');
		});
	};

	$scope.refreshMeasurements = function() {
		console.log('doing refreshMeasurements');
		RaceService.getMeasurements($scope.currentRace).
		success(function(data, status, headers, config) {
			console.log('refreshMeasurements successful...');
			console.log(data);
			if(data['ok']==true) {
				$scope.measurements = data.measurements;
			} else {
			}
		}).
		error(function(data, status, headers, config) {
			console.log('refreshMeasurements failed...');
		});
	};

	$scope.refreshTeam = function() {
		RaceService.getTeam($scope.currentRace).
		success(function(data, status, headers, config) {
			console.log('refreshTeam successful...');
			console.log(data);
			if(data['ok']==true) {
				$scope.team = data.team;
				if(data.team.drivers.length > 0) {
					$scope.selectedDriver = data.team.drivers[0];
				}
			} else {
			}
		}).
		error(function(data, status, headers, config) {
			console.log('refreshDrivers failed...');
		});
	};

	$scope.setSelectedDriver = function(driver) {
		$scope.selectedDriver = driver;
	};

	$scope.addDrive = function() {
		RaceService.addDrive($scope.currentRace, $scope.selectedDriver, $scope.selectedLapamount).
		success(function(data, status, headers, config) {
			console.log('addDrive successful...');
			console.log(data);
			if(data['ok']==true) {
				$scope.refreshDrives();
			} else {
			}
		}).
		error(function(data, status, headers, config) {
			console.log('addDrive failed...');
		});
	};

	$scope.addBatchDrives = function() {
		//do the adddrive action for all the drivers and the selected lapamount
		//if only one driver is there: trivial, call addDrive instead
		if($scope.team.drivers.length==1) {
			$scope.addDrive();
			return;
		}
		//more than one driver present!
		var finalpromise = undefined;
		var team = $scope.team;
		for(var i = 0; i<team.drivers.length; i++) {
			var iddriver = team.drivers[i].iddriver;
			console.log('adding batch drives for...'+iddriver);
			(function(i) {
				var icopy = i;
				console.log('doing it for the icopy:'+icopy+' driver '+iddriver);
				if (icopy == 0) {
					//start up the sequence
					console.log('queueing this: '+icopy);
					finalpromise = RaceService.addDrive($scope.currentRace, team.drivers[icopy], $scope.selectedLapamount);
				} else {
					//the rest: this does not need to resolve, just add to the sequence of promises
					finalpromise = finalpromise.then(function(data, status, headers, config) {
						// console.log($scope.team.drivers[i].iddriver+'gets added to queue');
						console.log('got success, queueing this: '+icopy);
						console.log(data);
						return RaceService.addDrive($scope.currentRace, team.drivers[icopy], $scope.selectedLapamount);
					});
				}
			})(i);
		}

		//now listen to the end of the promise...
		console.log('going to listen to the end...');
		finalpromise.then(function(data, status, headers, config) {
			console.log('wellllll, last one finished, will refresh now');
			console.log(data);
			$scope.refreshDrives();
		});

	};

	$scope.deleteDrive = function(drivenr, idrace) {
		RaceService.deleteDrive(drivenr, idrace).
		success(function(data, status, headers, config) {
			console.log('deleteDrive successful...');
			console.log(data);
			if(data['ok']==true) {
				$scope.refreshDrives();
			} else {
			}
		}).
		error(function(data, status, headers, config) {
			console.log('deleteDrive failed...');
		});
	};

	$scope.addMeasurementNow = function() {
		RaceService.addMeasurementNow($scope.currentRace).
		success(function(data, status, headers, config) {
			console.log('addMeasurementNow successful...');
			console.log(data);
			if(data['ok']==true) {
				$scope.refreshMeasurements();
			} else {
			}
		}).
		error(function(data, status, headers, config) {
			console.log('addMeasurementNow failed...');
		});
	};

	$scope.addMeasurementRelative = function() {
		RaceService.addMeasurementRelative($scope.currentRace, $scope.relativeRaceTime).
		success(function(data, status, headers, config) {
			console.log('addMeasurementRelative successful...');
			console.log(data);
			if(data['ok']==true) {
				$scope.refreshMeasurements();
			} else {
			}
		}).
		error(function(data, status, headers, config) {
			console.log('addMeasurementRelative failed...');
		});
	};

	$scope.deleteMeasurement = function(idmeasurement) {
		RaceService.deleteMeasurement(idmeasurement).
		success(function(data, status, headers, config) {
			console.log('deleteMeasurement successful...');
			console.log(data);
			if(data['ok']==true) {
				$scope.refreshMeasurements();
			} else {
			}
		}).
		error(function(data, status, headers, config) {
			console.log('deleteMeasurement failed...');
		});
	};

	$scope.refreshMeasurements();
	$scope.refreshDrives();
	$scope.refreshTeam();
}]);
