package utils

import (
	"github.com/shirou/gopsutil/v4/cpu"
	"github.com/shirou/gopsutil/v4/load"
	"github.com/shirou/gopsutil/v4/mem"
)

/*
	获取系统相关信息
*/

type SysInfo struct {
	CPUPercent       float64 `json:"cpuPercent"`       // CPU使用率
	LoadAverage1     float64 `json:"loadAverage1"`     // 1分钟内平均负载
	LoadAverage5     float64 `json:"loadAverage5"`     // 5分钟平均负载
	LoadAverage15    float64 `json:"loadAverage15"`    // 15分钟平均负载
	MemTotal         uint64  `json:"memTotal"`         // 总内存
	SwapTotal        uint64  `json:"swapTotal"`        // 总swap
	MemUsage         uint64  `json:"memUsage"`         // 已使用内存
	SwapUsage        uint64  `json:"swapUsage"`        // 已使用swap
	MemUsagePercent  float64 `json:"memUsagePercent"`  // 已使用内存百分比
	SwapUsagePercent float64 `json:"swapUsagePercent"` // 已使用swap百分比
}

func GetSysInfo() (*SysInfo, error) {
	result := SysInfo{}
	l, err := load.Avg()
	if err != nil {
		return nil, err
	}
	c, err := cpu.Percent(0, false)
	if err != nil {
		return nil, err
	}
	result.CPUPercent = c[0]
	result.LoadAverage1 = l.Load1
	result.LoadAverage5 = l.Load5
	result.LoadAverage15 = l.Load15
	sm, err := mem.SwapMemory()
	if err != nil {
		return nil, err
	}
	result.SwapTotal = sm.Total
	result.SwapUsage = sm.Used
	result.SwapUsagePercent = sm.UsedPercent
	vm, err := mem.VirtualMemory()
	if err != nil {
		return nil, err
	}
	result.MemTotal = vm.Total
	result.MemUsage = vm.Used
	result.MemUsagePercent = vm.UsedPercent
	return &result, nil
}
