package com.imdroid.sideslope.server.udp;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioDatagramChannel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component;

/**
 * @author Layton
 * @date 2023/2/13 11:47
 */
@Component
public class RtcmUdpServer implements ApplicationRunner {

    private final Logger logger = LoggerFactory.getLogger(RtcmUdpServer.class);

    @Value("${netty.data.port:9903}")
    private Integer port;

    @Autowired
    private RtcmUdpHandler rtcmUdpHandler;

    public RtcmUdpServer() {

    }

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


    private void start0() {
        EventLoopGroup group = new NioEventLoopGroup();
        Bootstrap bootstrap = new Bootstrap();
        bootstrap.group(group)
                .channel(NioDatagramChannel.class)
                .option(ChannelOption.SO_SNDBUF, 1024*1024) //1M缓存，考虑1000个基站同时转发
                .option(ChannelOption.SO_RCVBUF, 1024*1024)//1M缓存，断点续传要大带宽
                .handler(rtcmUdpHandler);
        try {
            ChannelFuture future = bootstrap.bind(port).sync().channel().closeFuture();
            logger.info("udp server start at port {}", port);
            future.await();
        } catch (Exception e) {
            logger.error("Error starting Imdroid protocol at port {}", port, e);
        } finally {
            group.shutdownGracefully();
        }
    }
}
