package com.its.dsrc.xnettcp.dsrc;

import com.its.app.utils.NettyUtils;
import com.its.app.utils.OS;
import com.its.dsrc.config.RunningConfig;
import com.its.dsrc.xnettcp.dsrc.codec.DsrcTcpServerEncoder;
import com.its.dsrc.xnettcp.dsrc.handler.DsrcAsn1ServerPacketInboundHandler;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.epoll.Epoll;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

@Slf4j
@RequiredArgsConstructor
@Service
public class DsrcTcpCommServerService {

    private final RunningConfig config;
    private final DsrcTcpServerEncoder dsrcTcpServerEncoder;
    private final DsrcAsn1ServerPacketInboundHandler dsrcAsn1ServerPacketInboundHandler;

    private EventLoopGroup acceptGroups = null;
    private EventLoopGroup workerGroups = null;
    private ServerBootstrap serverBootstrap = null;
    private ChannelFuture channelFuture = null;

    public void run() {
        if (!OS.isWindows()) {
            if (!Epoll.isAvailable()) {
                Epoll.unavailabilityCause().printStackTrace();
            }
        }
        if (NettyUtils.isEpollAvailable()) {
            log.info("서버가 리눅스 EPOLL 모드에서 실행됩니다.");
        }
        else {
            log.info("서버가 윈도우 NIO 모드에서 실행됩니다.");
        }

        this.serverBootstrap = createBootstrap();

        log.info("*********************************************************************************");
        log.info("**                    DSRC Communication Server Information                    **");
        log.info("**     bindAddress: {}", this.config.getCommBindingAddr());
        log.info("**      listenPort: {}", this.config.getCommBindingPort());
        log.info("**         backlog: {}", this.config.getCommBacklog());
        log.info("**   acceptThreads: {}", this.config.getCommAcceptThreads());
        log.info("**   workerThreads: {}", this.config.getCommWorkerThreads());
        log.info("*********************************************************************************");

        try {
            if (this.config.getCommBindingAddr().equals("0.0.0.0")) {
                this.channelFuture = this.serverBootstrap.bind(this.config.getCommBindingPort());
            }
            else {
                this.channelFuture = this.serverBootstrap.bind(this.config.getCommBindingAddr(), config.getCommBindingPort());
            }
        }
        catch (Exception e) {
            log.error("start, InterruptedException");
            this.acceptGroups.shutdownGracefully();
            this.workerGroups.shutdownGracefully();
        }
    }

    public void stop() {
        try {
            this.acceptGroups.shutdownGracefully().sync();
            this.workerGroups.shutdownGracefully().sync();
            this.channelFuture.channel().closeFuture().sync();
        } catch (InterruptedException e) {
            log.error("stop, InterruptedException");
        }
    }

    public ServerBootstrap createBootstrap() {
        ServerBootstrap serverBootstrap = new ServerBootstrap();
        EventLoopGroup acceptGroups;
        EventLoopGroup workerGroups;

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

        serverBootstrap.option(ChannelOption.AUTO_READ, true);
        serverBootstrap.option(ChannelOption.SO_BACKLOG, config.getCommBacklog());
        serverBootstrap.option(ChannelOption.SO_RCVBUF, config.getCommRcvBuf());
        serverBootstrap.option(ChannelOption.SO_REUSEADDR, true);
        serverBootstrap.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, config.getCommConnectTimeoutSeconds()*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 알고리즘 비활성화

        DsrcTcpCommServerInitializer dsrcTcpCommServerInitializer = new DsrcTcpCommServerInitializer(
                this.config,
                this.dsrcAsn1ServerPacketInboundHandler,
                this.dsrcTcpServerEncoder
        );
        serverBootstrap.childHandler(dsrcTcpCommServerInitializer);

        return serverBootstrap;
    }

}
