package cn.reghao.autodop.dmaster.machine.model.po;

import cn.reghao.autodop.common.machine.Cpu;
import cn.reghao.autodop.common.machine.Machine;
import cn.reghao.autodop.common.machine.Memory;
import cn.reghao.autodop.dmaster.util.db.BaseEntity;
import cn.reghao.jdkutil.machine.OsDetail;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import org.hibernate.annotations.LazyCollection;
import org.hibernate.annotations.LazyCollectionOption;

import javax.persistence.ElementCollection;
import javax.persistence.Entity;
import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author reghao
 * @date 2020-12-25 17:53:15
 */
@NoArgsConstructor
@Getter
@Setter
@Entity
public class MachineInfo  extends BaseEntity<Integer> {
    private String machineId;
    private String machineIpv4;
    private String arch;
    private String name;
    // 系统版本或内核版本
    private String version;
    private String byteOrder;
    private LocalDateTime bootTime;

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

    private long memTotal;
    private long memUsed;
    private long memAvail;
    @ElementCollection(targetClass = NetworkInfo.class)
    @LazyCollection(LazyCollectionOption.FALSE)
    private List<NetworkInfo> networkInfos;
    @ElementCollection(targetClass = DiskInfo.class)
    @LazyCollection(LazyCollectionOption.FALSE)
    private List<DiskInfo> diskInfos;

    public MachineInfo(Machine.MachineDetail machineDetail) {
        this.machineId = machineDetail.getMachineId();

        OsDetail osDetail = machineDetail.getOsDetail();
        this.arch = osDetail.getArch();
        this.name = osDetail.getName();
        this.version = osDetail.getVersion();
        this.byteOrder = osDetail.getByteOrder();
        this.bootTime = osDetail.getBootTime();

        Cpu.CpuDetail cpuDetail = machineDetail.getCpuDetail();
        this.physicalCore = cpuDetail.getPhysicalCore();
        this.logicalCore = cpuDetail.getLogicalCore();
        this.vendorId = cpuDetail.getVendorId();
        this.modelName = cpuDetail.getModelName();
        this.bogoMips = getBogoMips();

        Memory.MemoryDetail memoryDetail = machineDetail.getMemoryDetail();
        this.memTotal = memoryDetail.getTotal();
        this.memUsed = memoryDetail.getUsed();
        this.memAvail = memoryDetail.getFree();

        this.networkInfos = machineDetail.getNetworkDetails().stream().map(NetworkInfo::new).collect(Collectors.toList());
        this.diskInfos = machineDetail.getDiskDetails().stream().map(DiskInfo::new).collect(Collectors.toList());
        this.machineIpv4 = networkInfos.isEmpty() ? "127.0.0.1" : networkInfos.get(0).getIpv4();
    }
}
