package cn.reghao.autodop.common.machine;

import cn.reghao.jdkutil.text.TextFile;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;

import java.io.Serializable;
import java.util.*;

/**
 * 处理器
 *
 * @author reghao
 * @date 2019-10-25 13:12:36
 */
@Slf4j
public class Cpu {
    private final TextFile textFile;

    public Cpu(TextFile textFile) {
        this.textFile = textFile;
    }

    public CpuDetail detail() {
        List<String> list = textFile.read(LinuxProc.CPU_INFO);
        if (list.isEmpty()) {
            log.error("CPU 信息获取失败");
            return null;
        }

        List<Map<String, String>> result = new ArrayList<>();
        Map<String, String> map = new HashMap<>();
        for (String line : list) {
            if (!line.isEmpty()) {
                String[] kv = line.replace("\t", " ").split(":");
                if (kv.length == 2) {
                    map.put(kv[0].toLowerCase().trim(), kv[1].trim());
                }
            } else {
                result.add(map);
                map = new HashMap<>();
            }
        }

        if (result.isEmpty()) {
            log.error("CPU 信息获取失败");
            return null;
        }

        Map<String, String> info = result.get(0);
        CpuDetail cpuInfo = new CpuDetail();
        // TODO Raspbian 系统没有此字段
        String cpuCores = info.get("cpu cores");
        if (cpuCores != null) {
            cpuInfo.setPhysicalCore(Integer.parseInt(cpuCores));
        }

        cpuInfo.setVendorId(info.get("vendor_id"));
        cpuInfo.setModelName(info.get("model name"));
        cpuInfo.setBogoMips(info.get("bogomips"));

        Map<String, String> info1 = result.get(result.size()-1);
        cpuInfo.setLogicalCore(Integer.parseInt(info1.get("processor")) + 1);
        return cpuInfo;
    }

    @Data
    public static class CpuDetail implements Serializable {
        private static final long serialVersionUID = 1L;

        private int physicalCore;
        private int logicalCore;
        private String vendorId;
        private String modelName;
        private String bogoMips;
    }
}
