package com.inspect.base.core.utils;

import cn.hutool.system.oshi.CpuInfo;
import cn.hutool.system.oshi.OshiUtil;
import com.alibaba.fastjson.JSONObject;

import java.math.BigDecimal;

import oshi.hardware.GlobalMemory;

public class SystemInfo {
    private static BigDecimal GB_NUM = BigDecimal.valueOf(1073741824L);

    public static JSONObject getSystemInfo() {
        JSONObject result = new JSONObject();
        CpuInfo cpuInfo = OshiUtil.getCpuInfo();
        double free = cpuInfo.getFree();
        BigDecimal cpuUsed = BigDecimal.valueOf(100.0D).subtract(BigDecimal.valueOf(free)).setScale(2, 2);
        result.put("cpuUsed", cpuUsed);
        result.put("cpuFree", Double.valueOf(free));

        GlobalMemory memory = OshiUtil.getMemory();
        if (null != memory) {
            long memoryTotal = memory.getTotal();
            long available = memory.getAvailable();
            BigDecimal memoryFree = BigDecimal.valueOf(available).multiply(BigDecimal.valueOf(100L)).divide(BigDecimal.valueOf(memoryTotal), 2, 2);
            BigDecimal memoryUsed = BigDecimal.valueOf(100L).subtract(memoryFree);
            result.put("memoryUsed", memoryUsed);
            result.put("memoryFree", memoryFree);
            result.put("totalMemory", BigDecimal.valueOf(memoryTotal).divide(GB_NUM, 2, 2).toPlainString() + "GB");
            result.put("availableMemory", BigDecimal.valueOf(available).divide(GB_NUM, 2, 2).toPlainString() + "GB");
            result.put("usedMemory", BigDecimal.valueOf(memoryTotal - available).divide(GB_NUM, 2, 2).toPlainString() + "GB");
        }

        return result;
    }
}
