package com.skr.mdm.util;

import com.skr.mdm.bean.vo.index.SysStatusInfoVO;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import java.io.BufferedReader;
import java.io.File;
import java.io.InputStreamReader;
import java.text.DecimalFormat;
import java.util.Properties;

/**
 * 获取服务器系统
 */
@Slf4j
public class ServerSystemUtil {

    public static String osName() {
        Properties properties = System.getProperties();
        String osName = properties.getProperty("os.name");
        return osName.toLowerCase();
    }

    public static String userDir() {
        Properties properties = System.getProperties();
        return properties.getProperty("user.dir");
    }

    public static String getFilePath(String fileName) {
        String path = userDir();
        if (ServerSystemUtil.osName().contains("win")) {
            path += "\\";
        } else {
            path += "/";
        }
        return path + fileName;
    }

    /**
     * 获取已占用内存
     *
     * @return
     * @throws Exception
     */
    public static long getMemUsed() throws Exception {
        long memUsed = 0;
        Runtime rt = Runtime.getRuntime();
        Process p = rt.exec("top -b -n 1");// call "top" command in linux
        try (BufferedReader in = new BufferedReader(new InputStreamReader(p.getInputStream()))) {
            String str;
            int linecount = 0;
            while ((str = in.readLine()) != null) {
                linecount++;
                if (linecount == 4) {
                    memUsed = getMemUsed(str);
                    break;
                }
            }
        }
        return memUsed;
    }

    public static long getMemUsed(String info) {
        String[] split = StringUtils.split(info, ",");
        String used = split[2];
        String[] s = StringUtils.split(used, " ");
        return Long.valueOf(s[0]);
    }

    /**
     * 磁盘信息
     * @return
     */
    public static SysStatusInfoVO diskInfo(String diskPath) {
        File diskPartition = new File(diskPath);
        long usableSpace = diskPartition.getUsableSpace();
        long totalSpace = diskPartition.getTotalSpace();
        long useSpace = totalSpace - usableSpace;
        usableSpace = usableSpace / 1024 / 1024 / 1024;
        totalSpace = totalSpace / 1024 / 1024 / 1024;
        useSpace = useSpace / 1024 / 1024 / 1024;
        double diskUsageRate = Double.parseDouble(String.valueOf(useSpace)) / Double.parseDouble(String.valueOf(totalSpace));
        return SysStatusInfoVO.builder()
                .totalSpace(totalSpace + "G")
                .usableSpace(usableSpace + "G")
                .useSpace(useSpace + "G")
                .diskUsageRate(new DecimalFormat("0.00%").format(diskUsageRate))
                .build();
    }

}
