package net.hyperic.sigar.cmd;

import net.hyperic.sigar.SigarProxy;
import net.hyperic.sigar.SigarException;
import net.hyperic.sigar.SigarNotImplementedException;

import java.text.SimpleDateFormat;
import java.util.Date;

public class Uptime extends SigarCommandBase {

    public Uptime(Shell shell) {
        super(shell);
    }

    public Uptime() {
        super();
    }

    public String getUsageShort() {
        return "Show how long the system has been running";
    }

    public void output(String[] args) throws SigarException {
        System.out.println(getInfo(this.sigar));
    }

    public static String getInfo(SigarProxy sigar) throws SigarException {
        double uptime = sigar.getUptime().getUptime();

        String loadAverage;

        try {
            double[] avg = sigar.getLoadAverage();
            loadAverage = "load average: " +
                          avg[0] + ", " + avg[1] + ", " + avg[2];
        } catch (SigarNotImplementedException e) {
            loadAverage = "(load average unknown)";
        }

        return
            "  " + getCurrentTime() + 
            "  up " + formatUptime(uptime) +
            ", " + loadAverage;
    }

    private static String formatUptime(double uptime) {
        String retval = "";

        int days = (int)uptime / (60*60*24);
        int minutes, hours;

        if (days != 0) {
            retval += days + " " + ((days > 1) ? "days" : "day") + ", ";
        }

        minutes = (int)uptime / 60;
        hours = minutes / 60;
        hours %= 24;
        minutes %= 60;

        if (hours != 0) {
            retval += hours + ":" + minutes;
        }
        else {
            retval += minutes + " min";
        }

        return retval;
    }

    private static String getCurrentTime() {
        return new SimpleDateFormat("h:mm a").format(new Date());
    }

    //pretty close to uptime command, but we don't output number of users yet
    public static void main(String[] args) throws Exception {
        new Uptime().processCommand(args);
    }
}

@@ -157,16 +157,60 @@
 ception;
+%0Aimport net.hyperic.sigar.util.PrintfFormat;
 %0A%0Aimport
@@ -310,16 +310,161 @@
 Base %7B%0A%0A
+    private static Object%5B%5D loadAvg = new Object%5B3%5D;%0A%0A    private static PrintfFormat formatter =%0A        new PrintfFormat(%22%25.2f, %25.2f, %25.2f%22);%0A%0A
     publ
@@ -1031,100 +1031,215 @@
 adAv
-erage = %22load average: %22 +%0A                          avg%5B0%5D + %22, %22 + avg%5B1%5D + %22, %22 + avg%5B2%5D;
+g%5B0%5D = new Double(avg%5B0%5D);%0A            loadAvg%5B1%5D = new Double(avg%5B1%5D);%0A            loadAvg%5B2%5D = new Double(avg%5B2%5D);%0A%0A            loadAverage = %22load average: %22 +%0A                formatter.sprintf(loadAvg);%0A
 %0A   

format load average