/*
 * Copyright (c) 2015 Ziver
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 */

package wa.server.plugin.hwstatus;

import org.hyperic.sigar.*;
import org.hyperic.sigar.cmd.Shell;
import wa.server.plugin.WAStatus;
import zutil.StringUtil;
import zutil.io.file.FileUtil;
import zutil.parser.DataNode;
import zutil.parser.DataNode.DataType;

import java.io.IOException;
import java.util.Map;

/**
 * Created by Ziver on 2015-04-07.
 */
public class HwStatus implements WAStatus {
    @Override
    public String getName() {
        return "Hardware Summary";
    }

    @Override
    public String html() {
        try {
            return FileUtil.getContent(FileUtil.findURL("wa/server/plugin/hwstatus/HwStatus.tmpl"));
        } catch (IOException e) {
            return e.getMessage();
        }
    }

    @Override
    public void jsonUpdate(Map<String, String> request, DataNode root) {
        try{
            Sigar sigar = new Shell().getSigar();

            if(request.containsKey("uptime")){
                root.set("uptime",
                        StringUtil.formatTimeToString(
                                (long)sigar.getUptime().getUptime()));
            }
            if(request.containsKey("cpu")) {
                DataNode cpuNode = new DataNode(DataType.List);
                CpuInfo cpu_info = sigar.getCpuInfoList()[0];
                for (CpuPerc cpu : sigar.getCpuPercList()) {
                    cpuNode.add(Math.round(cpu.getCombined() * 100.0) / 100.0);
                }
                root.set("cpu", cpuNode);
            }
            if(request.containsKey("memory")) {
                DataNode memNode = new DataNode(DataType.Map);
                Mem mem = sigar.getMem();
                memNode.set("free", sizeByteToMB(mem.getFree()));
                memNode.set("used", sizeByteToMB(mem.getUsed()));
                root.set("memory", memNode);

                DataNode swapNode = new DataNode(DataType.Map);
                Swap swap = sigar.getSwap();
                swapNode.set("free", sizeByteToMB(swap.getFree()));
                swapNode.set("used", sizeByteToMB(swap.getUsed()));
                root.set("swap", swapNode);
            }
            if(request.containsKey("proc")) {
                DataNode procListNode = new DataNode(DataType.List);

                long[] pids = sigar.getProcList();
                //long[] pids = Shell.getPids(sigar, new String[0]);
                for( long pid : pids ) {
                    DataNode procNode = new DataNode(DataType.Map);

                    procNode.set("pid", pid);
                    try {
                        procNode.set("mem", sizeByteToMB(sigar.getProcMem(pid).getSize()));
                        procNode.set("user", sigar.getProcCredName(pid).getUser());
                        procNode.set("cputime", sigar.getProcTime(pid).getTotal() / 1000);
                        ProcCpu cpu = sigar.getProcCpu(pid);
                        procNode.set("cpu", CpuPerc.format(cpu.getPercent()));
                    }catch(Exception e){}
                    procNode.set("cmd", ProcUtil.getDescription(sigar, pid) );

                    procListNode.add(procNode);
                }
                root.set("proc", procListNode);
            }
        } catch (SigarException e) {
            e.printStackTrace();
        }
    }

    /**
     * Takes in a size of B and returns MB
     */
    private static long sizeByteToMB(long size){
        return size/(1024*1024);
    }
}
