package ink.wgink.module.instantmessage.websocket.channel;

import ink.wgink.module.instantmessage.service.IMessageService;
import ink.wgink.module.instantmessage.websocket.handler.WebSocketHandler;
import ink.wgink.module.instantmessage.service.IWebSocketTextCustomService;
import ink.wgink.properties.websocket.WebSocketProperties;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpServerCodec;
import io.netty.handler.logging.LoggingHandler;
import io.netty.handler.stream.ChunkedWriteHandler;


/**
 * @ClassName: WebSocketChannelInitializer
 * @Description: WebSocket
 * @Author: wanggeng
 * @Date: 2021/9/11 11:38 上午
 * @Version: 1.0
 */
public class WebSocketChannelInitializer extends ChannelInitializer<SocketChannel> {

    private WebSocketProperties webSocketProperties;
    private IWebSocketTextCustomService IWebSocketTextCustomService;
    private IMessageService messageService;

    @Override
    protected void initChannel(SocketChannel socketChannel) throws Exception {
        //设置log监听器，并且日志级别为debug，方便观察运行流程
        socketChannel.pipeline().addLast("logging", new LoggingHandler("DEBUG"));
        //设置解码器
        socketChannel.pipeline().addLast("http-codec", new HttpServerCodec());
        //聚合器，使用websocket会用到
        socketChannel.pipeline().addLast("aggregator", new HttpObjectAggregator(65536));
        //用于大数据的分区传输
        socketChannel.pipeline().addLast("http-chunked", new ChunkedWriteHandler());
        //自定义的业务handler
        WebSocketHandler webSocketHandler = new WebSocketHandler();
        webSocketHandler.setWebSocketProperties(webSocketProperties);
        webSocketHandler.setWebSocketTextCustomHandler(IWebSocketTextCustomService);
        webSocketHandler.setMessageService(messageService);
        socketChannel.pipeline().addLast("handler", webSocketHandler);
    }

    public void setWebSocketProperties(WebSocketProperties webSocketProperties) {
        this.webSocketProperties = webSocketProperties;
    }

    public void setWebSocketTextCustomHandler(IWebSocketTextCustomService IWebSocketTextCustomService) {
        this.IWebSocketTextCustomService = IWebSocketTextCustomService;
    }

    public void setMessageService(IMessageService messageService) {
        this.messageService = messageService;
    }
}
