package SBC;

/**
 * Untuk olah data dari /proc/stat
 * Mencari CPU usage
 * https://stackoverflow.com/questions/23367857/accurate-calculation-of-cpu-usage-given-in-percentage-in-linux
 * @author rdkartono
 *
 */
public class cpudata {
	public  String name;
	public  long user;
	public  long nice;
	public  long system;
	public  long idle;
	public  long iowait;
	public  long irq;
	public  long softirq;
	public  long steal;
	public  long guest;
	public  long guest_nice;
	public boolean correct_data;
	
	public cpudata(String vv) {
		String ww[] = vv.split("\\s+");
		
		try {
			name=ww[0].trim();
			
			if (name.startsWith("cpu")) {
				user=getlong(ww[1]);
				nice=getlong(ww[2]);
				system=getlong(ww[3]);
				idle=getlong(ww[4]);
				iowait=getlong(ww[5]);
				irq=getlong(ww[6]);
				softirq=getlong(ww[7]);
				steal=getlong(ww[8]);
				guest=getlong(ww[9]);
				guest_nice=getlong(ww[10]);
				correct_data = true;	
			} else {
				correct_data = false;
				
			}
			
		} catch(ArrayIndexOutOfBoundsException | NumberFormatException e) {
			correct_data = false;
		}
	}
	
	private long getlong(String ss) throws NumberFormatException {
		ss = ss.trim();
		return Long.parseLong(ss);	
	}
	
	/**
	 * IdleData = idle + iowait
	 * @return IdleData (Long)
	 */
	public long getIdleData() {
		if (correct_data) {
			return idle+iowait;
		} else return 0;
	}
	
	/**
	 * BusyData = user + nice + system + irq + softirq + steal
	 * @return BusyData (Long)
	 */
	public long getBusyData() {
		if (correct_data) {
			return user+nice+system+irq+softirq+steal;
		} else return 0;
	}
	
	/**
	 * TotalData = IdleData + BusyData
	 * @return TotalData (Long)
	 */
	public long getTotalData() {
		if (correct_data) {
			return getIdleData()+getBusyData();
		} else return 0;
	}
	
	/**
	 * Get CPU Usage, in percentage
	 * @param prev : previous cpudata. if null, then will calculate total average cpu_usage since boot
	 * @return CPU Usage (double)
	 */
	public double getCPU_Usage(cpudata prev) {
		long prev_total = 0;
		long prev_idle = 0;
		if (prev != null) {
			if (prev.correct_data) {
				prev_total = prev.getTotalData();
				prev_idle =prev.getIdleData();
			}
		}
		
		long delta_total = getTotalData() - prev_total;
		long delta_idle = getIdleData() - prev_idle;
		
		double result = delta_total - delta_idle;
		result = (result / delta_total) * 100;
		return Math.round(result * 10.0) / 10.0;		// pembulatan 1 desimal
	}
}
