package com.tsi.app.common.xnet;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;

public class ServerBootstrapFactory {

    public static ServerBootstrap createBootstrap(NettyServerConfig config, ChannelInitializer<Channel> channelInitializer) throws Exception {
        ServerBootstrap serverBootstrap = new ServerBootstrap();
        EventLoopGroup acceptGroups;
        EventLoopGroup workerGroups;

        acceptGroups = NettyUtils.newEventLoopGroup(config.getAcceptThreads(), "Accept");
        workerGroups = NettyUtils.newEventLoopGroup(config.getWorkerThreads(), "Worker");
        serverBootstrap.channel(NettyUtils.getServerSocketChannel());
        serverBootstrap.group(acceptGroups, workerGroups);

        serverBootstrap.option(ChannelOption.AUTO_READ, true);
        serverBootstrap.option(ChannelOption.SO_BACKLOG, config.getBacklog());
        serverBootstrap.option(ChannelOption.SO_RCVBUF, config.getRcvBuf());
        serverBootstrap.option(ChannelOption.SO_REUSEADDR, true);
        serverBootstrap.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, config.getConnectTimeoutSeconds()*1000);

        serverBootstrap.childOption(ChannelOption.SO_LINGER, 0);           // 4way-handshake 비활성
        serverBootstrap.childOption(ChannelOption.SO_KEEPALIVE, false);    // KEEPALIVE 비활성(활성: true)
        serverBootstrap.childOption(ChannelOption.SO_REUSEADDR, true);     // 소켓 재사용
        serverBootstrap.childOption(ChannelOption.TCP_NODELAY, true);      // Nagle 알고리즘 비활성화
        serverBootstrap.childHandler((ChannelHandler)channelInitializer);

        return serverBootstrap;
    }
}
