angular.module('bananaraceApp.controllers').controller('DriverCtrl', ['$scope', '$routeParams', 'DriverService', function($scope, $routeParams, DriverService) {
	//fetch all drivers for the given team
	var drivers = [];

	$scope.currentTeam = $routeParams.idteam;
	$scope.currentChampionship = $routeParams.idchampionship;

	$scope.refreshDrivers = function() {
		console.log('doing refreshTeams');
		var idchampionship = $routeParams.idchampionship;
		var idteam = $routeParams.idteam;
		DriverService.getDrivers(idchampionship, idteam).
		success(function(data, status, headers, config) {
			console.log('refreshDrivers successful...');
			console.log(data);
			if(data['ok']==true) {
				$scope.drivers = data.drivers;
			} else {
			}
		}).
		error(function(data, status, headers, config) {
			console.log('refreshTeams failed...');
		});
	};

	$scope.addDriver = function(newdriver) {
		var idchampionship = $routeParams.idchampionship;
		var idteam = $routeParams.idteam;
		console.log('controller adding driver... '+idchampionship+' '+idteam);
		DriverService.addDriver(newdriver, idchampionship, idteam).
			success(function(data, status, headers, config) {
				console.log(data);
				if(data['ok']==true) {
						$scope.refreshDrivers();
						newdriver.name = "";
				}
			}).
			error(function(data, status, headers, config) {
				console.log('addDriver failed...');
			}
		);;
	};

	$scope.deleteDriver = function(driver) {
		var idchampionship = $routeParams.idchampionship;
		var idteam = $routeParams.idteam;
		console.log('controller deleting driver... ');
		console.log(driver);
		DriverService.deleteDriver(driver).
			success(function(data, status, headers, config) {
				console.log(data);
				if(data['ok']==true) {
						$scope.refreshDrivers();
				}
			}).
			error(function(data, status, headers, config) {
				console.log('deleteDriver failed...');
			}
		);
	};

	$scope.refreshDrivers();
}]);
