package org.framework.lazy.cloud.network.heartbeat.server.init;


import lombok.extern.slf4j.Slf4j;
import org.framework.lazy.cloud.network.heartbeat.server.netty.filter.NettyServerFilter;
import org.framework.lazy.cloud.network.heartbeat.server.netty.socket.NettyOnCloudNettyServerSocket;
import org.framework.lazy.cloud.network.heartbeat.server.properties.ServerNodeProperties;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.autoconfigure.web.ServerProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.wu.framework.core.utils.ObjectUtils;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;


/**
 * description 初始化服务端
 *
 * @author 吴佳伟
 * @date 2023/09/12 18:22
 */
@Slf4j
@Configuration
public class InitServerSocket implements CommandLineRunner {

    private final ServerProperties serverProperties;
    private final NettyServerFilter nettyServerFilter;
    private final ServerNodeProperties serverNodeProperties;


    ThreadPoolExecutor NETTY_SERVER_EXECUTOR = new ThreadPoolExecutor(1, 1, 200, TimeUnit.MILLISECONDS,
            new ArrayBlockingQueue<>(1));

    public InitServerSocket(ServerProperties serverProperties,
                            NettyServerFilter nettyServerFilter,
                            ServerNodeProperties serverNodeProperties
    ) {
        this.serverProperties = serverProperties;
        this.nettyServerFilter = nettyServerFilter;
        this.serverNodeProperties = serverNodeProperties;
    }


    @Bean(destroyMethod = "shutdown")
    public NettyOnCloudNettyServerSocket nettyServerSocket() {
        return new NettyOnCloudNettyServerSocket(nettyServerFilter);
    }

    /**
     * @param args
     * @throws Exception
     */
    @Override
    public void run(String... args) throws Exception {

        log.info("Init InitServerSocket ...");
        NettyOnCloudNettyServerSocket serverSocket = new NettyOnCloudNettyServerSocket(nettyServerFilter);
        log.info("当前服务启动端口:{}", serverProperties.getPort());
        int serverPortAdd1000 = serverProperties.getPort() + 1000;
        if (!ObjectUtils.isEmpty(serverNodeProperties.getNodePort())) {
            serverPortAdd1000 = serverNodeProperties.getNodePort();
        }
        int nettyServerPort = serverPortAdd1000;
        Thread thread = new Thread(() -> {
            try {
                serverSocket.startServer(nettyServerPort);
            } catch (Exception e) {
                throw new RuntimeException(e);
            }

        });
        log.info("当前服务启动Netty端口:{}", nettyServerPort);
        NETTY_SERVER_EXECUTOR.execute(thread);

    }
}
