app.controller('resourcesController', function($scope, $http, $routeParams, $location) {			
	$scope.resources = [];
	$scope.tmpRes = {};
	$scope.tmpContent = "loading...";
	$scope.type = $routeParams.type;
	$scope.typeDesc = {};
	
	$scope.reload = function() {
		call_http_get($http, './ajax/resourceTypes/' + encodeURIComponent($scope.type) + '?' + $.now(), function(res) {			
			$scope.typeDesc = res.data;			
		});
	
		call_http_get($http, './ajax/resources/' + encodeURIComponent($scope.type) + '?' + $.now(), function(res) {			
			$scope.resources = res.data;			
		});			
	};
	
	$scope.prepareNewResource = function() {
		$scope.tmpRes = {
			'name'        : '',
			'description' : '',
			'content'     : ''
		};
	}
	
	$scope.prepareEditMetadata = function(r) {
		$scope.tmpRes = angular.copy(r);
	}
	
	$scope.prepareEditContent = function(r) {
		$scope.tmpRes = angular.copy(r);
		$scope.tmpContent = "loading...";
		call_http_get($http, './ajax/resources/' + encodeURIComponent(r.id) + '/content?' + $.now(), function(res) {
			if (res.data instanceof Object) {
				$scope.tmpContent = JSON.stringify(res.data, null, "\t");
			} else {
				$scope.tmpContent = res.data;
			}
		});
	}

	$scope.createNewResource = function(r) {
		params_http_post($http, './ajax/resources/?' + $.now(), $.param({
			'name' : r.name,
			'type' : $scope.type,
			'description' : r.description,
			'content' : r.content
		}), function(res) {
			alert("Resource saved");
			$('#newResourceModal').modal('hide');
			$scope.reload();
		});			
	}
			
	$scope.saveMetadata = function(id, md) {
		json_http_post($http, './ajax/resources/' + encodeURIComponent(id) + '/metadata?' + $.now(), md, function(res) {			
			alert("Resource saved");
			$scope.reload();
		});			
	};
	
	$scope.saveContent = function(id, content) {
		params_http_post($http, './ajax/resources/' + encodeURIComponent(id) + '/content?' + $.now(), $.param({
			'content' : content
		}), function(res) {
			alert("Resource saved");
			$('#editContentModal').modal('hide');
		});			
	};
				
	$scope.deleteResource = function(r) {			
		if (confirm("Are you sure ?")) {			
			call_http_delete($http, './ajax/resources/' + encodeURIComponent(r.id) + '?' + $.now(), function(res) {			
				alert("Resource deleted");
				$scope.reload();
			});			
		}			
	};			

	if      ($scope.type == 'context')    { $location.url("/contexts");  } 
	else if ($scope.type == 'vocabulary') { $location.url("/vocs");      } 
	else if ($scope.type == 'protocol')   { $location.url("/protocols"); } 
	else                                  { $scope.reload(); }			
});
