package com.its.dsrc.xnettcp.dsrc;

import com.its.dsrc.config.RunningConfig;
import com.its.dsrc.xnettcp.dsrc.codec.DsrcTcpServerDecoder;
import com.its.dsrc.xnettcp.dsrc.codec.DsrcTcpServerEncoder;
import com.its.dsrc.xnettcp.dsrc.handler.DsrcAsn1ServerIdleStateConnectionHandler;
import com.its.dsrc.xnettcp.dsrc.handler.DsrcAsn1ServerPacketInboundHandler;
import io.netty.channel.Channel;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.handler.timeout.IdleStateHandler;
import lombok.RequiredArgsConstructor;

import java.util.concurrent.TimeUnit;

@RequiredArgsConstructor
public class DsrcTcpCommServerInitializer extends ChannelInitializer<Channel> {

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

    @Override
    protected void initChannel(Channel channel) throws Exception {
        IdleStateHandler idleStateHandler = new IdleStateHandler(
                this.config.getCommReaderIdleTimeSeconds(),
                this.config.getCommWriterIdleTimeSeconds(),
                this.config.getCommAllIdleTimeSeconds(),
                TimeUnit.SECONDS);

        DsrcAsn1ServerIdleStateConnectionHandler connectionHandler = new DsrcAsn1ServerIdleStateConnectionHandler(this.config);

        ChannelPipeline pipeline = channel.pipeline();
        //pipeline.addLast(new LoggingHandler(LogLevel.WARN));
        pipeline.addLast("dsrcAsn1ServerConnectionIdleStateHandler", idleStateHandler);
        pipeline.addLast("dsrcAsn1ServerConnectionHandler", connectionHandler);
        pipeline.addLast("dsrcAsn1ServerDecoder", new DsrcTcpServerDecoder(this.config));  // Decoding handler
        pipeline.addLast("dsrcAsn1ServerPacketInboundHandler", this.dsrcAsn1ServerPacketInboundHandler); // packet distribute handler add
        pipeline.addLast("dsrcAsn1ServerEncoder", this.dsrcTcpServerEncoder);  // Encoding handler
    }

}
