package com.inspect.patrol.linkage;

import com.inspect.patrol.linkage.handler.UdpServerHandler;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelOption;
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.Value;
import org.springframework.boot.CommandLineRunner;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.stereotype.Component;

@Component
@EnableAsync
public class NettyUdpServer implements CommandLineRunner {
    private static final Logger logger = LoggerFactory.getLogger(NettyUdpServer.class);
    @Value("${patrol.video.netty_udp_server_port}")
    private String nettyUdpServerPort;

    @Async
    public void run(String... args) {
        NettyUdpServer nettyUdpServer = new NettyUdpServer();
        nettyUdpServer.init(Integer.parseInt(this.nettyUdpServerPort));
    }

    public void init(int port) {
        NioEventLoopGroup bossLoopGroup = new NioEventLoopGroup();

        try {
            Bootstrap serverBootstrap = new Bootstrap();
            serverBootstrap = serverBootstrap.group(bossLoopGroup);
            serverBootstrap = serverBootstrap.channel(NioDatagramChannel.class);
            serverBootstrap = serverBootstrap.option(ChannelOption.SO_BROADCAST, Boolean.TRUE);
            serverBootstrap = serverBootstrap.handler(new UdpServerHandler());
            ChannelFuture channelFuture = serverBootstrap.bind(port).sync();
            logger.info("started and listened on: {} ", channelFuture.channel().localAddress());
            channelFuture.channel().closeFuture().sync();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            logger.info("netty udp close!");
            bossLoopGroup.shutdownGracefully();
        }

    }
}
