package ch.polgrabia.demos;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class PingPongServer implements Runnable {
    private static final Logger logger = LoggerFactory.getLogger(PingPongHandler.class);
    private final int port;

    public PingPongServer(int port) {
        this.port = port;
    }

    @Override
    public void run() {
        var bossGroup = new NioEventLoopGroup();
        var workerGroup = new NioEventLoopGroup();
        try {
            ServerBootstrap sb = new ServerBootstrap();
            sb.group(bossGroup, workerGroup)
                    .channel(NioServerSocketChannel.class)
                    .childHandler(new ChannelInitializer<>() {
                        @Override
                        protected void initChannel(Channel channel) {
                            channel.pipeline().addLast(new PingPongHandler());
                        }
                    })
                    .option(ChannelOption.SO_BACKLOG, 128)
                    .childOption(ChannelOption.SO_KEEPALIVE, true);

            ChannelFuture channelFuture = sb.bind(port)
                    .addListener(
                            (ChannelFutureListener) cf ->
                                    logger.info("PingPongServer started on port: %d".formatted(port)))
                    .sync();
            channelFuture.channel().closeFuture().sync();
        } catch (InterruptedException e) {
            logger.error("We got interrupted", e);
        }
    }
}
