package cn.reghao.tnb.message.app.config;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.stereotype.Component;
import org.springframework.web.context.WebApplicationContext;

import java.net.*;
import java.util.Enumeration;
import java.util.HashSet;
import java.util.Set;

/**
 * @author reghao
 * @date 2022-03-28 11:54:49
 */
@Slf4j
@Component
public class SpringLifecycle implements ApplicationRunner, DisposableBean {
    private final WebApplicationContext applicationContext;
    private String nodeId = "";

    public SpringLifecycle(WebApplicationContext applicationContext) {
        this.applicationContext = applicationContext;
    }

    @Override
    public void run(ApplicationArguments args) {
        Set<String> ipv4AddressSet = getAddress();
        // 通过 vm option -Dserver.address=192.168.0.10 指定
        String serverAddress1 = System.getProperty("server.address");
        // 通过环境变量 NODE_ADDRESS=192.168.0.10 指定时端口会绑定到该地址, 只会监听 192.168.0.10:6002
        String serverAddress = System.getenv("NODE_ADDRESS");
        if (!ipv4AddressSet.contains(serverAddress)) {
            log.error("没有通过环境变量 NODE_ADDRESS 指定地址, 或是指定的地址不是机器地址 {}, 结束 MessageService 进程...", ipv4AddressSet);
            System.exit(SpringApplication.exit(applicationContext));
        }

        int serverPort = 0;
        String serverPortStr = applicationContext.getEnvironment().getProperty("server.port");
        if (serverPortStr != null) {
            serverPort = Integer.parseInt(serverPortStr);
        }

        this.nodeId = String.format("%s_%s", serverAddress.replace(".", "_"), serverPort);
        log.info("MessageService 启动...");
    }

    @Override
    public void destroy() {
        log.info("MessageService 停止...");
    }

    private Set<String> getAddress() {
        Set<String> ipv4AddressSet = new HashSet<>();
        try {
            Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();
            // 遍历主机的网络接口
            while (interfaces.hasMoreElements()) {
                NetworkInterface iface = interfaces.nextElement();
                String ifaceName = iface.getName();
                Enumeration<InetAddress> inetAddrs = iface.getInetAddresses();
                while (inetAddrs.hasMoreElements()) {
                    InetAddress address = inetAddrs.nextElement();
                    /*if (!address.isLoopbackAddress()) {
                    }*/
                    if (address instanceof Inet4Address) {
                        ipv4AddressSet.add(address.getHostAddress());
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return ipv4AddressSet;
    }

    public String getNodeId() {
        return this.nodeId;
    }
}
