package com.mx.cneeds.server.wechat.websocket;

import com.mx.cneeds.server.wechat.common.codec.InvocationDecoder;
import com.mx.cneeds.server.wechat.common.codec.InvocationEncoder;
import com.mx.cneeds.server.wechat.common.codec.MessageToWebSocketEncoder;
import com.mx.cneeds.server.wechat.common.dispatcher.MessageDispatcher;
import com.mx.cneeds.server.wechat.websocket.handler.NettyServerHandler;
import com.mx.cneeds.server.wechat.websocket.handler.OperateWebsocketHandler;
import io.netty.channel.Channel;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpServerCodec;
import io.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler;
import io.netty.handler.stream.ChunkedWriteHandler;
import io.netty.handler.timeout.ReadTimeoutHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.util.concurrent.TimeUnit;

@Component
public class NettyServerHandlerInitializer extends ChannelInitializer<Channel> {

    /**
     * 心跳超时时间
     */
    private static final Integer READ_TIMEOUT_SECONDS = 3 * 60;

    @Autowired
    private NettyServerHandler nettyServerHandler;

    @Autowired
    private OperateWebsocketHandler operateWebsocketHandler;

    @Override
    protected void initChannel(Channel ch) {
        // 获得 Channel 对应的 ChannelPipeline
        ChannelPipeline channelPipeline = ch.pipeline();
        // 添加一堆 NettyServerHandler 到 ChannelPipeline 中
        channelPipeline
                // 空闲检测
                // .addLast(new ReadTimeoutHandler(READ_TIMEOUT_SECONDS, TimeUnit.SECONDS))

                //websocket协议本身是基于http协议的，所以这边也要使用http解编码器
                .addLast(new HttpServerCodec())
                //以块的方式来写的处理器
                .addLast(new ChunkedWriteHandler())
                .addLast(new HttpObjectAggregator(8192))

                // 编码器
                // .addLast(new InvocationEncoder())
                .addLast(new MessageToWebSocketEncoder())

                // 操作
                .addLast(operateWebsocketHandler)
                // 服务端处理器
                .addLast(nettyServerHandler)
                .addLast(new WebSocketServerProtocolHandler(
                        "/ws", null, true, 65536 * 10));
    }
}
