package cn.reghao.devops.mgr.machine.model.po;

import cn.reghao.devops.common.msg.constant.NodeStatus;
import cn.reghao.devops.mgr.util.BaseEntity;
import cn.reghao.devops.common.msg.event.EvtAgentStart;
import cn.reghao.jutil.jdk.machine.data.detail.*;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import org.hibernate.annotations.LazyCollection;
import org.hibernate.annotations.LazyCollectionOption;

import javax.persistence.*;
import javax.validation.constraints.NotNull;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author reghao
 * @date 2020-12-25 17:53:15
 */
@NoArgsConstructor
@Getter
@Setter
@Entity
@Table(name = "devops_machine_info")
public class MachineInfo extends BaseEntity {
    @Column(unique = true, nullable = false)
    private String machineId;
    @NotNull
    private String machineIpv4;
    @NotNull
    private String arch;
    @NotNull
    private String name;
    // 系统版本或内核版本
    @NotNull
    private String version;
    @NotNull
    private String byteOrder;
    @NotNull
    private Long bootTime;
    @NotNull
    private String agentVersion;
    private Integer stat;

    @NotNull
    @ElementCollection(targetClass = NetworkInfo.class)
    @LazyCollection(LazyCollectionOption.FALSE)
    @CollectionTable(name = "devops_machine_info_networks")
    private List<NetworkInfo> networkInfos;

    @NotNull
    @ElementCollection(targetClass = DiskInfo.class)
    @LazyCollection(LazyCollectionOption.FALSE)
    @CollectionTable(name = "devops_machine_info_disks")
    private List<DiskInfo> diskInfos;

    public MachineInfo(EvtAgentStart 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();
        this.agentVersion = machineDetail.getAppVersion().getCommitId();
        this.stat = NodeStatus.Online.getCode();

        setNetworkInfos(machineDetail.getNetworkDetails());
        setDiskInfos(machineDetail.getDiskDetails());
    }

    private void setNetworkInfos(List<NetworkDetail> networkDetails) {
        this.networkInfos = networkDetails.stream().map(NetworkInfo::new).collect(Collectors.toList());
        this.machineIpv4 = networkInfos.isEmpty() ? "127.0.0.1" : networkInfos.get(0).getIpv4();
    }

    private void setDiskInfos(List<DiskDetail> diskDetails) {
        this.diskInfos = diskDetails.stream().map(DiskInfo::new).collect(Collectors.toList());
    }
}
