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

import cn.reghao.autodop.common.msg.pub.dto.node.constant.NodeStatus;
import cn.reghao.autodop.dmaster.app.model.constant.EnvList;
import cn.reghao.autodop.dmaster.util.db.BaseEntity;
import cn.reghao.autodop.dmaster.notification.model.po.NotifyGroup;
import lombok.*;
import org.hibernate.annotations.LazyCollection;
import org.hibernate.annotations.LazyCollectionOption;

import javax.persistence.*;
import java.time.LocalDateTime;
import java.util.List;

/**
 * @author reghao
 * @date 2021-06-29 09:36:13
 */
@NoArgsConstructor
@Getter
@Setter
@Entity
public class MachineHost extends BaseEntity<Integer> {
    @Column(unique = true, nullable = false)
    private String machineId;
    private String machineIpv4;
    private LocalDateTime bootTime;
    private String osArch;
    private String osName;
    private String osVersion;
    private String env;
    private String status;
    private long lastCheck;
    @Embedded
    private SshAuth sshAuth;
    @ManyToMany(cascade = CascadeType.REFRESH)
    @JoinColumn(name = "notify_group_id", foreignKey = @ForeignKey(value = ConstraintMode.NO_CONSTRAINT))
    @LazyCollection(LazyCollectionOption.FALSE)
    private List<NotifyGroup> notifyGroups;

    // TODO 根据机器所属的地区，机房等维度来分组
    public MachineHost(MachineInfo machineInfo) {
        this.machineId = machineInfo.getMachineId();
        List<NetworkInfo> list = machineInfo.getNetworkInfos();
        if (!list.isEmpty()) {
            this.machineIpv4 = list.get(0).getIpv4();
        } else {
            this.machineIpv4 = "127.0.0.1";
        }
        this.bootTime = machineInfo.getBootTime();
        this.osArch = machineInfo.getArch();
        this.osName = machineInfo.getName();
        this.osVersion = machineInfo.getVersion();

        this.env = EnvList.test.name();
        this.status = NodeStatus.Online.name();
        this.lastCheck = System.currentTimeMillis();
    }
}
