package net.hyperic.sigar;

import java.util.HashMap;
import java.util.Map;

/**
 * Extend ProcTime to provide process cpu percentage metric.
 */
public class ProcCpu extends ProcTime {

    private static ProcCpu key = new ProcCpu();
    private static Map ptable = new HashMap();

    private long lastTime = 0;
    private long pid;
    private double percent = 0.0;

    private void getValues(Sigar sigar, long pid)
        throws SigarException {
        this.nativeGet(sigar, pid);
    }

    static synchronized ProcCpu get(Sigar sigar, long pid)
        throws SigarException {

        ProcCpu cpu;

        key.pid = pid;
        cpu = (ProcCpu)ptable.get(key);

        if (cpu == null) {
            cpu = new ProcCpu();
            cpu.pid = pid;
            ptable.put(cpu, cpu);
        }

        long timeNow = System.currentTimeMillis() / 1000; //seconds
        double diff = timeNow - cpu.lastTime;
        if (diff == 0) {
            return cpu; //we were just called within < 1 second ago.
        }

        cpu.lastTime = timeNow;

        long otime = cpu.total;

        cpu.getValues(sigar, pid);

        if (otime == 0) {
            //XXX could/should pause first time called.
            return cpu;
        }

        cpu.percent = ((cpu.total - otime) / diff);
        if (cpu.percent >= 1.0) {
            cpu.percent = 0.99;
        }

        return cpu;
    }

    /**
     * @return Process CPU usage percentage.
     */
    public double getPercent() {
        return this.percent;
    }

    /**
     * @return Pid of the process.
     */
    public int hashCode() {
        return (int)this.pid;
    }

    public boolean equals(Object cpu) {
        if (!(cpu instanceof ProcCpu)) {
            return false;
        }

        return ((ProcCpu)cpu).pid == this.pid;
    }
}

@@ -278,29 +278,31 @@
 p();%0A%0A    pr
-ivate
+otected
  long lastTi
@@ -319,35 +319,15 @@
   pr
-ivate long pid;%0A    priva
+otec
 te
+d
  dou
@@ -344,16 +344,40 @@
 t = 0.0;
+%0A    protected long pid;
 %0A%0A    pr

make some fields protected