var module = angular.module('repoEnablerUI', []);

module.controller('repoEnablerCtrl', function ($scope, $http, $sce, $location) {
	$scope.currType = '';
	$scope.repos = [];
	$scope.types = getTypologies();
	$scope.repoFilter = { name: '' };
	
	common_init($scope, $http, $sce, $location)
	
	$scope.selectType = function(type) {
	
		if (type != $scope.currType) {
			$scope.repos = [];
			$scope.currType = type;
			$scope.repoFilter = { name: '' };
		}
		
		$scope.showSpinner();
		$http.get('listRepositories.json?type=' + type).success(
			function(data) {
				$scope.repos = data;
				hideSpinner();
			})
		.error(
			function() {
				scope.showError("An error occurred while fetching datasource of type " + type);
				$scope.hideSpinner();
			});
	}
	
	$scope.setValidation = function(id, valid) {
		$scope.showSpinner();
		
		$http.get('validateRepo.do?b=' +valid + "&id=" + id).success(
            function(data) {
            	var newId = data;
            	angular.forEach($scope.repos, function(r) {
            		if (r.id == id) {
            			r.id = newId;
            			r.valid = valid;
            		}
            	});
            	$scope.hideSpinner();
            }
        ).error(
            function() {
            	if (valid == false) {
            		$scope.showError('An error occurred: please verify that there are no workflows related to this dataprovider');
            	} else {
            		$scope.showError('An error occurred validating the dataprovider');
            	}
            	$scope.hideSpinner();
            }
        );
	};

	if ($scope.types.length > 0) {
		$scope.selectType($scope.types[0].name);
	}

});
