(function()
{
	var moduleName = 'claromentis.project';
	var module;

	try {
		module = angular.module(moduleName);
	} catch(err) {
		// named module does not exist, so create one
		module = angular.module(moduleName, []);
	}

	module
		.filter("sanitize", ['$sce', sanitizeFilter])
		.controller("historyCtrl", ["$scope", "$http", historyController]);

	function sanitizeFilter($sce)
	{
		return function(htmlCode){
			// Convert repeated metadata from an object to a string
			if (typeof htmlCode === 'object')
				htmlCode = htmlCode[Object.keys(htmlCode)[0]];
			return $sce.trustAsHtml(htmlCode);
		}
	}

	function historyController($scope, $http)
	{
		$scope.history = history_items;
		$scope.updateHistoryData = function(data)
		{
			$scope.type = data.type;
			$scope.object_id = data.objectId;
			$scope.itemsPerPage = data.itemsPerPage;
			$scope.currentPage = data.currentPage;
			$scope.totalItems = data.totalItems;
		};
		$scope.updateHistoryData(history_data);

		// Load new history data
		function getResultsPage(pageNumber)
		{
			var type = '';
			if ($scope.type === 'task')
				type = $scope.type + '/';

			$http.get('/api/projects/' + type + $scope.object_id + '/history?page=' + pageNumber)
				.then(function(result) {
					$scope.history = result.data.history;
					$scope.updateHistoryData(result.data.history_data);
				});
		}

		// If pagination is clicked
		$scope.pageChanged = function(newPage)
		{
			getResultsPage(newPage);
		};

		$scope.$on('updateHistoryLog', function(event, args)
		{
			getResultsPage($scope.currentPage);
		});
	}
}());
