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

import io.netty.channel.Channel;
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.udp.handler.NettyUdpServerPermeateClientTransferHandler;
import org.framework.lazy.cloud.network.heartbeat.common.adapter.ChannelTypeAdapter;
import org.framework.lazy.cloud.network.heartbeat.common.decoder.NettyProxyMsgDecoder;
import org.framework.lazy.cloud.network.heartbeat.common.encoder.NettyProxyMsgEncoder;
import org.framework.lazy.cloud.network.heartbeat.common.filter.DebugChannelInitializer;

/**
 * netty 客户端连接真实服服务端访客拦截器
 */
public class NettyUdpServerPermeateClientTransferFilter extends DebugChannelInitializer<SocketChannel> {
    private final ChannelTypeAdapter channelTypeAdapter;

    public NettyUdpServerPermeateClientTransferFilter(ChannelTypeAdapter channelTypeAdapter) {
        this.channelTypeAdapter = channelTypeAdapter;
    }

    /**
     * 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 NettyProxyMsgDecoder(Integer.MAX_VALUE, 0, 4, -4, 0));
//        pipeline.addLast(new NettMsgEncoder());
        pipeline.addLast(new NettyProxyMsgDecoder(Integer.MAX_VALUE, 0, 4, -4, 0));
        pipeline.addLast(new NettyProxyMsgEncoder());
        pipeline.addLast(new NettyUdpServerPermeateClientTransferHandler(channelTypeAdapter));
    }
}
