app.controller('wfHistoryController', function($scope, $http, $routeParams) {
	$scope.fromDate = $routeParams.from;
	$scope.toDate = $routeParams.to;
	$scope.maxNumberOfRecentWfs = $routeParams.total;

	$scope.workflows = [];
	$scope.currentWf = {};
	$scope.currDetailsKey = '';
	$scope.currDetailsValue = '';
	$scope.sortField = 'processId';
	$scope.sortReverse = false;
				
	$scope.reload = function() {
		var url = './ajax/wfs/?' + $.now();
		
		url += "&total=" + $scope.maxNumberOfRecentWfs;
		
		if ($scope.fromDate > 0) { url += "&from=" + $scope.fromDate; }
		if ($scope.toDate > 0) { url += "&to=" + $scope.toDate; }
		
		call_http_get($http, url, function(res) {			
			$scope.workflows = res.data;			
		});			
	};
	
	$scope.setCurrentWf = function(wf) {
		$scope.currentWf = angular.copy(wf);
		$scope.currDetailsKey = '';
		$scope.currDetailsValue = '';
		$scope.currentWf.arrayDetails = [];
		$scope.currentWf.duration = $scope.calculateDateDiff(parseInt(wf.details['system:startDate']), parseInt(wf.details['system:endDate']));
		
		angular.forEach(wf.details, function(v,k) {
			$scope.currentWf.arrayDetails.push({'k':k, 'v':v});
		});
	}
	
	$scope.setCurrentDetailParam = function(k, v) {
		$scope.currDetailsKey = k;
		$scope.currDetailsValue = v;
	}
	
	
	$scope.calculateDateDiff = function(start, end) {
		if (start <= 0 || end <= 0) {
			return '-';
		}
		var seconds = 0;
		var minutes = 0;
		var hours = 0;
		var days = 0;
		
		if (end > start) {
			seconds = Math.round((end - start) / 1000);
			if (seconds > 60) {
				minutes = Math.floor(seconds / 60);
				seconds = seconds % 60;
				if (minutes > 60) {
					hours = Math.floor(minutes / 60);
					minutes = minutes % 60;
					if (hours > 24) {
						days = Math.floor(hours / 24);
						hours = hours % 24;
					}
				}
			}
		}
		var res = '';
		if (days > 0) {
			if (res) { res += ', '; } 
			res += days + " day(s)"
		}
		if (hours > 0) {
			if (res) { res += ', '; } 
			res += hours + " hour(s)"
		}
		if (minutes > 0) {
			if (res) { res += ', '; } 
			res += minutes + " minute(s)"
		}
		if (seconds > 0) {
			if (res) { res += ', '; } 
			res += seconds + " second(s)"
		}
		if (!res) {
			res = '0 seconds';
		} 
		                
		return res;
	}
	
	$scope.reload();			
});