angular.module("robware").service('statusService', ["$http", function($http) {
	function parseProcessData(data) {
		var headers = data.shift();
		var cpuIndex = -1;
		var ignoreColNames = ["user", "pid", "vsz", "rss", "tty", "stat"];
		var ignoreCols = [];

		var processHeaders = []
		for (var col in headers) {
			if (headers[col].toLowerCase() === "%cpu")
				cpuIndex = col;

			if (ignoreColNames.indexOf(headers[col].toLowerCase()) > -1)
				ignoreCols.push(col);
			else
				processHeaders.push(headers[col]);
		}

		data.sort(function (a, b) {
			cpuA = parseFloat(a[cpuIndex]);
			cpuB = parseFloat(b[cpuIndex]);
			if (cpuA > cpuB)
				return -1;
			if (cpuA < cpuB)
				return 1
			return 0;
		});

		var processData = [];
		for (var row in data) {
			var obj = {};
			for (var col in data[row]) {
				if (ignoreCols.indexOf(col) === -1)
					obj[headers[col]] = data[row][col];
			}
			processData.push(obj);
		}

		return [processHeaders, processData];
	}
	
	this.getProcesses = function() {
		return $http.get('/status/getprocesses').then(function(response) {
			parsedData = parseProcessData(response.data);
			return {headers: parsedData[0], data: parsedData[1]};
		});
	};
	
	this.getSystemInfo=function(){
		return $http.get('/status/getsysteminfo').then(function(response){
			return response.data;
		});
	};
	
	this.getUptime=function(){
		return $http.get('/status/getuptime').then(function(response){
			return response.data;
		})
	};
}]);