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

import io.netty.channel.ChannelPipeline;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
import io.netty.handler.timeout.IdleStateHandler;
import org.framework.lazy.cloud.network.heartbeat.client.netty.tcp.handler.NettyTcpClientHandler;
import org.framework.lazy.cloud.network.heartbeat.client.netty.tcp.socket.NettyTcpClientSocket;
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;

public class NettyTcpClientFilter extends DebugChannelInitializer<SocketChannel> {


    private final ChannelTypeAdapter channelTypeAdapter;
    private final NettyTcpClientSocket nettyTcpClientSocket;

    public NettyTcpClientFilter(ChannelTypeAdapter channelTypeAdapter, NettyTcpClientSocket nettyTcpClientSocket) {
        this.channelTypeAdapter = channelTypeAdapter;
        this.nettyTcpClientSocket = nettyTcpClientSocket;
    }

    @Override
    protected void initChannel0(SocketChannel ch) throws Exception {
        ChannelPipeline pipeline = ch.pipeline();

        /* * 解码和编码，应和服务端一致 * */
//        pipeline.addLast(new NettyMsgDecoder(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("framer", new DelimiterBasedFrameDecoder(8192, Delimiters.lineDelimiter()));
        //入参说明: 读超时时间、写超时时间、所有类型的超时时间、时间格式
        //因为服务端设置的超时时间是5秒，所以设置4秒

        pipeline.addLast(new IdleStateHandler(0, 4, 0));
        pipeline.addLast("decoder", new StringDecoder());
        pipeline.addLast("encoder", new StringEncoder());
        pipeline.addLast("doHandler", new NettyTcpClientHandler(channelTypeAdapter, nettyTcpClientSocket)); //客户端的逻辑
    }
}