package cn.reghao.bnt.web.devops.machine.model.po;

import cn.reghao.bnt.common.msg.constant.NodeStatus;
import cn.reghao.bnt.common.msg.event.EvtAgentStart;
import cn.reghao.bnt.web.util.BaseEntity;
import cn.reghao.jutil.jdk.machine.data.detail.NetworkDetail;
import cn.reghao.jutil.jdk.machine.data.detail.OsDetail;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;

import jakarta.persistence.Column;
import jakarta.persistence.Entity;
import jakarta.persistence.Table;
import jakarta.validation.constraints.NotNull;
import java.util.List;

/**
 * @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;
    @NotNull
    private Integer stat;

    public MachineInfo(EvtAgentStart evtAgentStart) {
        this.machineId = evtAgentStart.getMachineId();
        OsDetail osDetail = evtAgentStart.getOsDetail();
        this.arch = osDetail.getArch();
        this.name = osDetail.getName();
        this.version = osDetail.getVersion();
        this.byteOrder = osDetail.getByteOrder();
        this.bootTime = osDetail.getBootTime();
        this.agentVersion = evtAgentStart.getAppVersion().getCommitId();
        this.stat = NodeStatus.Online.getCode();
        setNetworkInfos(evtAgentStart.getNetworkDetails());
    }

    private void setNetworkInfos(List<NetworkDetail> networkDetails) {
        this.machineIpv4 = networkDetails.isEmpty() ? "127.0.0.1" : networkDetails.get(0).getIpv4();
    }
}
