package com.imdroid.sideslope.server.tcp;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import io.netty.handler.timeout.IdleStateHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component;

@Component
public class RtcmTcpServer implements ApplicationRunner {
    private final Logger logger = LoggerFactory.getLogger(RtcmTcpServer.class);

    @Value("${netty.config.port}")
    private int port;

    @Override
    public void run(ApplicationArguments args) throws Exception {
        new Thread(this::start0, "tcp-server").start();
    }

    private void start0() {
        logger.info("rtcm tcp server starting...");
        // Configure the server.
        EventLoopGroup bossGroup = new NioEventLoopGroup(1);
        EventLoopGroup workerGroup = new NioEventLoopGroup();
        try {
            ServerBootstrap b = new ServerBootstrap();
            b.group(bossGroup, workerGroup)
                    .channel(NioServerSocketChannel.class)
                    .handler(new LoggingHandler(LogLevel.INFO))
                    .childHandler(new ChannelInitializer() {
                        @Override
                        protected void initChannel(Channel channel) throws Exception {
                            ChannelPipeline p = channel.pipeline();
                            //p.addLast(new IdleStateHandler(600, 600, 600));    //设置心跳超时时间，秒
                            p.addLast(new RtcmTcpHandler());
                        }
                    });
            Channel ch = b.bind(port).sync().channel();
            logger.info("tcp server start at port {}", port);
            ch.closeFuture().sync();
        } catch (Exception el) {
            logger.error(el.toString());
        } finally {
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }
    }
}
