package com.tsi.comm.server.tcp;

import com.tsi.app.common.app.AppUtils;
import com.tsi.app.common.utils.OS;
import com.tsi.app.common.xnet.NettyTcpServer;
import com.tsi.app.common.xnet.NettyUtils;
import com.tsi.comm.server.config.TsiCvimServerConfig;
import com.tsi.comm.server.tcp.codec.CvimServerByteBufMessageDecoder;
import com.tsi.comm.server.tcp.codec.CvimServerEncoder;
import com.tsi.comm.server.tcp.handler.CvimServerInboundMessageHandler;
import com.tsi.comm.server.tcp.initializer.CvimServerInitializer;
import io.netty.channel.epoll.Epoll;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;

@Service
public class TsiCvimServer extends NettyTcpServer {

    private final TsiCvimServerConfig config;
    private CvimServerByteBufMessageDecoder cvimServerByteBufMessageDecoder;
    private CvimServerInboundMessageHandler cvimServerInboundMessageHandler;
    private CvimServerEncoder cvimServerEncoder;

    public TsiCvimServer(TsiCvimServerConfig config) {
        super(config);

        this.config = config;
        this.cvimServerByteBufMessageDecoder = (CvimServerByteBufMessageDecoder) AppUtils.getBean(CvimServerByteBufMessageDecoder.class);
        this.cvimServerInboundMessageHandler = (CvimServerInboundMessageHandler)AppUtils.getBean(CvimServerInboundMessageHandler.class);
        this.cvimServerEncoder = (CvimServerEncoder) AppUtils.getBean(CvimServerEncoder.class);
    }

    @PostConstruct
    public void initialize() {
        super.setChannelInitializer(new CvimServerInitializer(this.config));
        if (!OS.isWindows()) {
            if (!Epoll.isAvailable()) {
                Epoll.unavailabilityCause().printStackTrace();
            }
        }
        if (NettyUtils.isEpollAvailable()) {
            System.out.println("서버가 리눅스 EPOLL 모드에서 실행됩니다.");
        }
        else {
            System.out.println("서버가 윈도우 NIO 모드에서 실행됩니다.");
        }
    }
}
