package com.yihu.hos.common.util;

import org.hyperic.sigar.*;

import java.net.InetAddress;
import java.net.URL;
import java.net.UnknownHostException;
import java.util.*;

/**
 * sigar 服务器硬件指标 工具类
 *
 * @author HZY
 * @vsrsion 1.0
 * Created at 2016/10/10.
 */
public class SigarUtil {

    public final static Sigar sigar = initSigar();

    private static Sigar initSigar() {
        try {
            //此处只为得到依赖库文件的目录，可根据实际项目自定义
            URL claaPath = SigarUtil.class.getResource("/");
            String path = System.getProperty("java.library.path");
            String sigarLibPath = claaPath.getPath();
            //为防止java.library.path重复加，此处判断了一下
            if (!path.contains(sigarLibPath)) {
                if (isOSWin()) {
                    path += ";" + sigarLibPath;
                } else {
                    path += ":" + sigarLibPath;
                }
                System.setProperty("java.library.path", path);
            }
            return new Sigar();
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    public URL getUrl() {
        return this.getClass().getResource("/");
    }

//    public static void main(String[] args) {
//        DecimalFormat df = new DecimalFormat("#0.00");
//        double d = 0;
//        String f = df.format(d);
//        double e = Double.parseDouble(String.format("%.2f", d));
//        System.out.println(e);
//    }

    /**
     * 是否是windows系统
     *
     * @return
     */
    public static boolean isOSWin() {//OS 版本判断
        String OS = System.getProperty("os.name").toLowerCase();
        if (OS.indexOf("win") >= 0) {
            return true;
        } else return false;
    }

    /* ==================================================   以下是打印测试   ========================================================================== */

    /**
     * 系统信息  jvm等
     *
     * @throws UnknownHostException
     */
    private static void property() throws UnknownHostException {
        Runtime r = Runtime.getRuntime();
        Properties props = System.getProperties();
        InetAddress addr;
        addr = InetAddress.getLocalHost();
        String ip = addr.getHostAddress();
        Map<String, String> map = System.getenv();
        String userName = map.get("USERNAME");// 获取用户名
        String computerName = map.get("COMPUTERNAME");// 获取计算机名
        String userDomain = map.get("USERDOMAIN");// 获取计算机域名
        System.out.println("用户名:    " + userName);
        System.out.println("计算机名:    " + computerName);
        System.out.println("计算机域名:    " + userDomain);
        System.out.println("本地ip地址:    " + ip);
        System.out.println("本地主机名:    " + addr.getHostName());
        System.out.println("JVM可以使用的总内存:    " + r.totalMemory());
        System.out.println("JVM可以使用的剩余内存:    " + r.freeMemory());
        System.out.println("JVM可以使用的处理器个数:    " + r.availableProcessors());
        System.out.println("Java的运行环境版本：    " + props.getProperty("java.version"));
        System.out.println("Java的运行环境供应商：    " + props.getProperty("java.vendor"));
        System.out.println("Java供应商的URL：    " + props.getProperty("java.vendor.url"));
        System.out.println("Java的安装路径：    " + props.getProperty("java.home"));
        System.out.println("Java的虚拟机规范版本：    " + props.getProperty("java.vm.specification.version"));
        System.out.println("Java的虚拟机规范供应商：    " + props.getProperty("java.vm.specification.vendor"));
        System.out.println("Java的虚拟机规范名称：    " + props.getProperty("java.vm.specification.name"));
        System.out.println("Java的虚拟机实现版本：    " + props.getProperty("java.vm.version"));
        System.out.println("Java的虚拟机实现供应商：    " + props.getProperty("java.vm.vendor"));
        System.out.println("Java的虚拟机实现名称：    " + props.getProperty("java.vm.name"));
        System.out.println("Java运行时环境规范版本：    " + props.getProperty("java.specification.version"));
        System.out.println("Java运行时环境规范供应商：    " + props.getProperty("java.specification.vender"));
        System.out.println("Java运行时环境规范名称：    " + props.getProperty("java.specification.name"));
        System.out.println("Java的类格式版本号：    " + props.getProperty("java.class.version"));
        System.out.println("Java的类路径：    " + props.getProperty("java.class.path"));
        System.out.println("加载库时搜索的路径列表：    " + props.getProperty("java.library.path"));
        System.out.println("默认的临时文件路径：    " + props.getProperty("java.io.tmpdir"));
        System.out.println("一个或多个扩展目录的路径：    " + props.getProperty("java.ext.dirs"));
        System.out.println("操作系统的名称：    " + props.getProperty("os.name"));
        System.out.println("操作系统的构架：    " + props.getProperty("os.arch"));
        System.out.println("操作系统的版本：    " + props.getProperty("os.version"));
        System.out.println("文件分隔符：    " + props.getProperty("file.separator"));
        System.out.println("路径分隔符：    " + props.getProperty("path.separator"));
        System.out.println("行分隔符：    " + props.getProperty("line.separator"));
        System.out.println("用户的账户名称：    " + props.getProperty("user.name"));
        System.out.println("用户的主目录：    " + props.getProperty("user.home"));
        System.out.println("用户的当前工作目录：    " + props.getProperty("user.dir"));
    }

    /**
     * 内存信息
     *
     * @return 返回单位 ：G
     * @throws SigarException
     */
    public static Map<String, Object> memory() throws SigarException {
        Mem mem = sigar.getMem();
        Swap swap = sigar.getSwap();
        Map<String, Object> memory = new HashMap<>();
        memory.put("total", getDouble((double)mem.getTotal() / 1024L / 1024L / 1024L));
        memory.put("used",  getDouble((double)mem.getUsed() / 1024L / 1024L / 1024L));
        memory.put("free",  getDouble((double)mem.getFree() / 1024L / 1024L / 1024L));
        memory.put("freePerc", getDouble(mem.getFreePercent() / 1024L / 1024L / 1024L));
        memory.put("usedPerc", getDouble(mem.getUsedPercent() / 1024L / 1024L / 1024L));
        //交换区
        memory.put("swapTotal", getDouble((double)swap.getTotal() / 1024L / 1024L / 1024L));
        memory.put("swapUsed",  getDouble((double)swap.getUsed() / 1024L / 1024L / 1024L));
        memory.put("swapFree", getDouble((double) swap.getFree() / 1024L / 1024L / 1024L));
        return memory;
    }

    /**
     * cpu使用情况
     *
     * @return
     * @throws SigarException
     */
    public static Map<String, Object> cpu() throws SigarException {
        Map<String, Object> cpuMap = new HashMap<>();
        CpuInfo infos[] = sigar.getCpuInfoList();
        CpuPerc cpuPerc = sigar.getCpuPerc();
        CpuInfo info1 = infos[0];
        //cpu信息
        cpuMap.put("quantity", infos.length);
        cpuMap.put("model", info1.getModel());
        cpuMap.put("totalCores", info1.getTotalCores());
        cpuMap.put("totalSockets", info1.getTotalSockets());
        cpuMap.put("Mhz", info1.getMhz());
        //cpu使用率

        String totalPerc = String.format("%.2f", cpuPerc.getCombined() * 100);
        String userPerc = String.format("%.2f", cpuPerc.getUser() * 100);
        String sysPerc = String.format("%.2f", cpuPerc.getSys() * 100);
        String wait = String.format("%.2f", cpuPerc.getWait() * 100);
        String nice = String.format("%.2f", cpuPerc.getNice() * 100);
        String freePerc = String.format("%.2f", cpuPerc.getIdle() * 100);

        cpuMap.put("totalPerc", getDouble(cpuPerc.getCombined() * 100));
        cpuMap.put("userPerc", getDouble(cpuPerc.getUser() * 100));
        cpuMap.put("sysPerc", getDouble(cpuPerc.getSys() * 100));
        cpuMap.put("wait", getDouble(cpuPerc.getWait() * 100));
        cpuMap.put("nice", getDouble(cpuPerc.getNice() * 100));
        cpuMap.put("freePerc", getDouble(cpuPerc.getIdle() * 100));
        return cpuMap;
    }


    /**
     * 操作系统信息
     */
    private static void os() {
        OperatingSystem OS = OperatingSystem.getInstance();
        // 操作系统内核类型如： 386、486、586等x86
        System.out.println("操作系统:    " + OS.getArch());
        System.out.println("操作系统CpuEndian():    " + OS.getCpuEndian());//
        System.out.println("操作系统DataModel():    " + OS.getDataModel());//
        // 系统描述
        System.out.println("操作系统的描述:    " + OS.getDescription());
        // 操作系统类型
        // System.out.println("OS.getName():    " + OS.getName());
        // System.out.println("OS.getPatchLevel():    " + OS.getPatchLevel());//
        // 操作系统的卖主
        System.out.println("操作系统的卖主:    " + OS.getVendor());
        // 卖主名称
        System.out.println("操作系统的卖主名:    " + OS.getVendorCodeName());
        // 操作系统名称
        System.out.println("操作系统名称:    " + OS.getVendorName());
        // 操作系统卖主类型
        System.out.println("操作系统卖主类型:    " + OS.getVendorVersion());
        // 操作系统的版本号
        System.out.println("操作系统的版本号:    " + OS.getVersion());
    }

    private static void who() throws SigarException {
        Who who[] = sigar.getWhoList();
        if (who != null && who.length > 0) {
            for (int i = 0; i < who.length; i++) {
                // System.out.println("当前系统进程表中的用户名" + String.valueOf(i));
                Who _who = who[i];
                System.out.println("用户控制台:    " + _who.getDevice());
                System.out.println("用户host:    " + _who.getHost());
                // System.out.println("getTime():    " + _who.getTime());
                // 当前系统进程表中的用户名
                System.out.println("当前系统进程表中的用户名:    " + _who.getUser());
            }
        }
    }

    /**
     * 硬盘信息
     */
    public static List<Map<String, Object>> file() {
        List<Map<String, Object>> files = new ArrayList<>();
        Map<String, Object> fileMap = null;
        FileSystem fslist[] = new FileSystem[0];
        try {
            fslist = sigar.getFileSystemList();
            for (int i = 0; i < fslist.length; i++) {
                FileSystem fs = fslist[i];
                fileMap = new HashMap<>();

                switch (fs.getType()) {
                    case 0: // TYPE_UNKNOWN ：未知
                        break;
                    case 1: // TYPE_NONE
                        break;
                    case 2: // TYPE_LOCAL_DISK : 本地硬盘
                        FileSystemUsage usage = sigar.getFileSystemUsage(fs.getDirName());
                        fileMap.put("devName", fs.getDevName());
                        fileMap.put("dirName", fs.getDirName());
                        fileMap.put("flags", fs.getFlags());
                        fileMap.put("sysTypeName", fs.getSysTypeName());
                        fileMap.put("typeName", fs.getTypeName());
                        fileMap.put("type", fs.getType());

                        fileMap.put("total", usage.getTotal() / 1024L / 1024L);
                        fileMap.put("free", usage.getFree() / 1024L / 1024L);
                        fileMap.put("aVall", usage.getAvail() / 1024L / 1024L);//可用大小
                        fileMap.put("used", usage.getUsed() / 1024L / 1024L);
                        fileMap.put("usePercent", usage.getUsePercent() * 100D);

                        fileMap.put("diskRead", usage.getDiskReads());
                        fileMap.put("diskWrite", usage.getDiskWrites());
                        files.add(fileMap);
                        break;
                    case 3:// TYPE_NETWORK ：网络
                        break;
                    case 4:// TYPE_RAM_DISK ：闪存
                        break;
                    case 5:// TYPE_CDROM ：光驱
                        break;
                    case 6:// TYPE_SWAP ：页面交换
                        break;
                }

            }
        } catch (SigarException e) {
            e.printStackTrace();
        }
        return files;
    }

    /**
     * 网络信息
     *
     * @throws Exception
     */
    public static Map<String, Object> net() {
        Map<String, Object> netMap = new HashMap<>();
        NetInterfaceConfig netConfig = null;
        try {
            netConfig = sigar.getNetInterfaceConfig();
            NetInterfaceStat netIfStat = sigar.getNetInterfaceStat(netConfig.getName());
            Map<String, Object> bps = populate(netConfig.getName());//bps
            netMap.put("address", netConfig.getAddress());
            netMap.put("broadcast", netConfig.getBroadcast());
            netMap.put("netmask", netConfig.getNetmask());
            netMap.put("rxPackets", netIfStat.getRxPackets());
            netMap.put("txPackets", netIfStat.getTxPackets());
            netMap.put("rxBytes", netIfStat.getRxBytes());
            netMap.put("txBytes", netIfStat.getTxBytes());
            netMap.put("txPackets", netIfStat.getTxPackets());
            netMap.put("txbps", bps.get("txbps"));
            netMap.put("rxbps", bps.get("rxbps"));
        } catch (SigarException e) {
            e.printStackTrace();
        }
        return netMap;
    }

    private static void ethernet() throws SigarException {
        String[] ifaces = sigar.getNetInterfaceList();
        for (int i = 0; i < ifaces.length; i++) {
            NetInterfaceConfig cfg = sigar.getNetInterfaceConfig(ifaces[i]);
            if (NetFlags.LOOPBACK_ADDRESS.equals(cfg.getAddress()) || (cfg.getFlags() & NetFlags.IFF_LOOPBACK) != 0
                    || NetFlags.NULL_HWADDR.equals(cfg.getHwaddr())) {
                continue;
            }
            System.out.println(cfg.getName() + "IP地址:" + cfg.getAddress());// IP地址
            System.out.println(cfg.getName() + "网关广播地址:" + cfg.getBroadcast());// 网关广播地址
            System.out.println(cfg.getName() + "网卡MAC地址:" + cfg.getHwaddr());// 网卡MAC地址
            System.out.println(cfg.getName() + "子网掩码:" + cfg.getNetmask());// 子网掩码
            System.out.println(cfg.getName() + "网卡描述信息:" + cfg.getDescription());// 网卡描述信息
            System.out.println(cfg.getName() + "网卡类型" + cfg.getType());//


        }
    }

    /**
     * 網絡傳輸速率 bps
     *
     * @param name
     * @throws SigarException
     */
    public static Map<String, Object> populate(String name)
            throws SigarException {
        Map<String, Object> bps = new HashMap<>();
        try {
            long start = System.currentTimeMillis();
            NetInterfaceStat statStart = sigar.getNetInterfaceStat(name);
            long rxBytesStart = statStart.getRxBytes();
            long txBytesStart = statStart.getTxBytes();
            Thread.sleep(1000);
            long end = System.currentTimeMillis();
            NetInterfaceStat statEnd = sigar.getNetInterfaceStat(name);
            long rxBytesEnd = statEnd.getRxBytes();
            long txBytesEnd = statEnd.getTxBytes();
            long rxbps = ((rxBytesEnd - rxBytesStart) * 8 / 1024) / ((end - start) / 1000);
            long txbps = ((txBytesEnd - txBytesStart) * 8 / 1024) / ((end - start) / 1000);
            bps.put("rxbps", rxbps);
            bps.put("txbps", txbps);
            System.out.println("#######rxbps: " + rxbps + " txbps: " + txbps);
        } catch (SigarException e) {
        } catch (Exception e) {
        }
        return bps;
    }

    /**
     * 获取两位小数的double值
     * @param value
     * @return
     */
    public static double getDouble(double value){
        String total = String.format("%.2f", value );
        return Double.parseDouble(total);
    }

}
