
/*=============================================================================================
	author:ZhaoJun
	version:1.2
	email:2732810281@qq.com
=============================================================================================*/


//严格模式
/*-------------------------------------------------------------------------------------------*/	
'use strict';
const _os = require('os');
/*-------------------------------------------------------------------------------------------*/

// 系统信息的操作
/*-------------------------------------------------------------------------------------------*/	
class info
{
	static platform()
	{ 
		return process.platform;
	}

	static cpuCount()
	{ 
		return _os.cpus().length;
	}

	static sysUptime()
	{ 
		//seconds
		return _os.uptime();
	}

	static processUptime()
	{ 
		//seconds
		return process.uptime();
	}

	static freemem()
	{
		return _os.freemem() / ( 1024 * 1024 );
	}

	static totalmem()
	{
		return _os.totalmem() / ( 1024 * 1024 );
	}

	static freemem()
	{
		return _os.freemem() / ( 1024 * 1024 );
	}

	static freememPercentage()
	{
		return _os.freemem() / _os.totalmem();
	}

	static async freeCommand()
	{
		let stdout = await $Sys.cmd('free -m');
		var lines = stdout.split("\n"); 
		var str_mem_info = lines[1].replace( /[\s\n\r]+/g,' ');
		
		var mem_info = str_mem_info.split(' ')
		total_mem    = parseFloat(mem_info[1])
		free_mem     = parseFloat(mem_info[3])
		buffers_mem  = parseFloat(mem_info[5])
		cached_mem   = parseFloat(mem_info[6])
		
		used_mem = total_mem - (free_mem + buffers_mem + cached_mem)
		return used_mem -2
	}

	// Hard Disk Drive
	static async harddrive()
	{	
		let stdout = await $Sys.cmd('df -k');
		var total = 0;
		var used = 0;
		var free = 0;
	
		var lines = stdout.split("\n");
		var str_disk_info = lines[1].replace( /[\s\n\r]+/g,' ');
		var disk_info = str_disk_info.split(' ');

		total = Math.ceil((disk_info[1] * 1024)/ Math.pow(1024,2));
		used = Math.ceil(disk_info[2] * 1024 / Math.pow(1024,2)) ;
		free = Math.ceil(disk_info[3] * 1024 / Math.pow(1024,2)) ;

		return [total, free, used]
	}

	// Return process running current 
	static async getProcesses(nProcess=0)
	{			
		let command = 'ps -eo pcpu,pmem,time,args | sort -k 1 -r | head -n'+10
		if (nProcess > 0)command = 'ps -eo pcpu,pmem,time,args | sort -k 1 -r | head -n'+(nProcess + 1)
		
		let stdout = await $Sys.cmd(command);
		var lines = stdout.split("\n");
		lines.shift()
		lines.pop()
	
		var result = []
		lines.forEach
		(
			function(_item,_i)
			{
				var _str = _item.replace( /[\s\n\r]+/g,' ');
				_str = _str.split(' ')   
				result.push([_str[1],_str[2],_str[3],_str[4].substring((_str[4].length - 25))])              
			}
		);
		return result;
	}

	/*
	* Returns All the load average usage for 1, 5 or 15 minutes.
	*/
	static Loadavg()
	{ 
		return _os.loadavg();
	}

	static binLoadavg(_time)
	{ 

		if(_time === undefined || (_time !== 5 && _time !== 15) ) _time = 1;
		
		var loads = _os.loadavg();
		var v = 0;
		if(_time == 1) v = loads[0];
		if(_time == 5) v = loads[1];
		if(_time == 15) v = loads[2];
			
		return v; 
	}

	static cpuFree()
	{ 
		return info.getCPUUsage(true);
	}
	
	static cpuUsage()
	{ 
		return info.getCPUUsage(false);
	}

	static getCPUUsage(free)
	{ 
		var stats1 = info.getCPUInfo();
		var startIdle = stats1.idle;
		var startTotal = stats1.total;
		
		return new Promise
		(
			function(reslove,reject)
			{
				setTimeout
				(
					function() 
					{
						try 
						{
							var stats2 = info.getCPUInfo();
							var endIdle = stats2.idle;
							var endTotal = stats2.total;
							
							var idle 	= endIdle - startIdle;
							var total 	= endTotal - startTotal;
							var perc	= idle / total;
							
							if(free === true)
							{
								reslove(perc)
							}
							else
							{
								reject( (1 - perc) );
							}
						} 
						catch (error) 
						{
							reject(error)
						}
					}, 1000 
				);
			}
		)
	}
	
	static getCPUInfo()
	{ 
		var cpus = _os.cpus();
		
		var user = 0;
		var nice = 0;
		var sys = 0;
		var idle = 0;
		var irq = 0;
		var total = 0;
		
		for(var cpu in cpus)
		{
			
			user += cpus[cpu].times.user;
			nice += cpus[cpu].times.nice;
			sys += cpus[cpu].times.sys;
			irq += cpus[cpu].times.irq;
			idle += cpus[cpu].times.idle;
		}
		
		var total = user + nice + sys + idle + irq;
		
		return {
			'idle': idle, 
			'total': total
		};
	}

}
/*-------------------------------------------------------------------------------------------*/    
module.exports=info;