package org.framework.lazy.cloud.network.heartbeat.server.netty.udp.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.common.InternalNetworkPenetrationRealClient;
import org.framework.lazy.cloud.network.heartbeat.common.adapter.ChannelFlowAdapter;
import org.framework.lazy.cloud.network.heartbeat.common.filter.DebugChannelInitializer;
import org.framework.lazy.cloud.network.heartbeat.server.netty.udp.handler.NettyUdpServerPermeateClientVisitorHandler;

public class NettyUdpServerPermeateClientVisitorFilter extends DebugChannelInitializer<SocketChannel> {
    private final InternalNetworkPenetrationRealClient internalNetworkPenetrationRealClient;
    private final ChannelFlowAdapter channelFlowAdapter;

    public NettyUdpServerPermeateClientVisitorFilter(InternalNetworkPenetrationRealClient internalNetworkPenetrationRealClient, ChannelFlowAdapter channelFlowAdapter) {
        this.internalNetworkPenetrationRealClient = internalNetworkPenetrationRealClient;
        this.channelFlowAdapter = channelFlowAdapter;
    }

    /**
     * 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 NettyUdpServerPermeateClientVisitorHandler(internalNetworkPenetrationRealClient, channelFlowAdapter));
    }
}
