package com.sjyt.icom.asst.context.handle.netty;

import com.sjyt.icom.asst.context.handle.wsframe.WsFrameEvent;
import com.sjyt.icom.asst.context.handle.wsframe.WsFrameHandleContext;
import com.sjyt.icom.asst.service.impl.ChannelPoolService;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.FullHttpRequest;
import io.netty.handler.codec.http.websocketx.WebSocketFrame;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * websocket消息处理类
 *
 * @author renyanru
 * @version V1.0.0
 * @date 2022/5/27 13:15
 */
@Slf4j
@ChannelHandler.Sharable
@Component
public class WebSocketHandler extends SimpleChannelInboundHandler<WebSocketFrame> {
    @Resource
    private ChannelPoolService channelPoolService;
    @Resource
    private WsFrameHandleContext wsFrameHandleConText;
    @Resource
    private ShakeHandsHandler shakeHandsHandler;

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        log.info("客户端连接：{}", ctx.channel().id());
        channelPoolService.addChannel(ctx.channel());
        super.channelActive(ctx);
    }


    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        log.info("客户端断开连接：{}", ctx.channel().id());
        channelPoolService.removeChannel(ctx.channel());
        channelPoolService.delUserChannel(ctx.channel());
        super.channelInactive(ctx);
    }

    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) {
        ctx.channel().flush();
    }

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, WebSocketFrame frame) {
        // 根据请求数据类型进行分发处理
        wsFrameHandleConText.doSomeTing(WsFrameEvent.builder().frame(frame).ctx(ctx).build());
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        log.info("客户端请求数据类型：{}", msg.getClass());
        if (msg instanceof FullHttpRequest) {
            shakeHandsHandler.fullHttpRequestHandler(ctx, (FullHttpRequest) msg);
        }
        super.channelRead(ctx, msg);
    }
}
