package org.framework.lazy.cloud.network.heartbeat.client.netty.tcp.filter;

import io.netty.channel.Channel;
import io.netty.channel.ChannelDuplexHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.socket.SocketChannel;
import org.framework.lazy.cloud.network.heartbeat.client.netty.InternalNetworkClientPermeateServerVisitor;
import org.framework.lazy.cloud.network.heartbeat.client.netty.tcp.handler.NettyTcpClientPermeateServerVisitorHandler;
import org.framework.lazy.cloud.network.heartbeat.common.filter.DebugChannelInitializer;

public class NettyTcpClientPermeateServerVisitorFilter extends DebugChannelInitializer<SocketChannel> {

    private final InternalNetworkClientPermeateServerVisitor internalNetworkClientPermeateServerVisitor;

    public NettyTcpClientPermeateServerVisitorFilter(InternalNetworkClientPermeateServerVisitor internalNetworkClientPermeateServerVisitor) {
        this.internalNetworkClientPermeateServerVisitor = internalNetworkClientPermeateServerVisitor;

    }

    /**
     * This method will be called once the {@link Channel} was registered. After the method returns this instance
     * will be removed from the {@link ChannelPipeline} of the {@link Channel}.
     *
     * @param ch the {@link Channel} which was registered.
     * @throws Exception is thrown if an error occurs. In that case it will be handled by
     *                   {@link #exceptionCaught(ChannelHandlerContext, Throwable)} which will by default connectionClose
     *                   the {@link Channel}.
     */
    @Override
    protected void initChannel0(SocketChannel ch) throws Exception {
        ChannelPipeline pipeline = ch.pipeline();
        pipeline.addLast(new ChannelDuplexHandler());
        pipeline.addLast(new NettyTcpClientPermeateServerVisitorHandler(internalNetworkClientPermeateServerVisitor));
    }
}
