import java.lang.management.ManagementFactory;
import java.lang.management.OperatingSystemMXBean;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.time.LocalDateTime;

import org.hyperic.sigar.ProcCpu;
import org.hyperic.sigar.ProcUtil;
import org.hyperic.sigar.Sigar;
import org.hyperic.sigar.SigarException;

/**
 * Check the CPU to find out if the page has finished loading.
 * 
 * @author JPR
 *
 */
public class CPUController
{

	/**
	 * Constructor
	 */
	public CPUController()
	{
	}

	/**
	 * return the percentage of CPU usage
	 * 
	 * @param page
	 *            used in logs
	 * @return the percentage of CPU usage
	 */
	public double getCpu() throws ErrorException
	{

		double cpu; // I'm searching for acrobat and explorer cpu
		double maxCpu; // To check if there's some value in cpu reading
		int watchDog = 0; // to detect about infinite loop
		do
		{
			maxCpu = 0.0f;
			cpu = 0.0f;
			System.out.println("");

			final Sigar sigar = new Sigar();
			final long[] processes;
			try
			{
				processes = sigar.getProcList();
			} catch (Exception e)
			{
				throw new ErrorException("can't access pids list", 1);
			}

			for (final long processId : processes)
			{
				try
				{
					ProcCpu procCpu = sigar.getProcCpu(processId);
					String name = ProcUtil.getDescription(sigar, processId);
					if (procCpu.getPercent() > 0.001f)
					{
						maxCpu = procCpu.getPercent();
						System.out.println(LocalDateTime.now().toString() + "\t" + name + "\t" + procCpu.getPercent());
						if (name.toLowerCase().contains("acrobat.exe") || name.toLowerCase().contains("explorer.exe"))
						{
							cpu = procCpu.getPercent();
						}
					}
				} catch (SigarException e)
				{
					// for denied access on some pid
				}

			}

			// check about infinite loop
			watchDog++;
			if (watchDog == 10)
			{
				throw new ErrorException("infinite loop, procCpu values always 0", 1);
			}

			if (maxCpu == 0.0f)
			{
				System.out.println(LocalDateTime.now().toString() + "\t ----->nothing found during getProcCpu reading. Already tried: \t" + "\t" + watchDog);
			} else
			{
				System.out.println(LocalDateTime.now().toString() + "\t ----->found this cpu for accrobat or explore \t" + "\t" + cpu);
			}

		} while (maxCpu == 0.0f);
		return cpu;
	}
}
