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

import cn.hutool.core.util.ObjectUtil;
import com.sjyt.icom.asst.common.exception.ShakeHandException;
import com.sjyt.icom.asst.common.util.UrlUtils;
import com.sjyt.icom.asst.conf.properties.WebSocketProperties;
import com.sjyt.icom.asst.service.impl.ChannelPoolService;
import com.sjyt.icom.asst.common.util.FuncUtils;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.http.FullHttpRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Map;

/**
 * 处理连接请求，客户端WebSocket发送握手包时会执行这一次请求
 *
 * @author renyanru
 * @version V1.0.0
 * @date 2022/6/2 10:25
 */
@Slf4j
@Component
public class ShakeHandsHandler {
    @Autowired
    private WebSocketProperties properties;
    @Resource
    private ChannelPoolService channelPoolService;

    public void fullHttpRequestHandler(ChannelHandlerContext ctx, FullHttpRequest request) {
        String uri = request.uri();
        Map<String, String> params = UrlUtils.getUrlParams(uri);
        //todo 校验用户合法性
        log.debug("客户端请求参数：{}", params);
        FuncUtils.isTrueOrFalse(params.size() > 0).trueOrFalseHandle(() -> {
            String identify = params.get("identify");
            FuncUtils.isTrue(ObjectUtil.isNotNull(identify)).trueHandle(() -> {
                Channel channel =channelPoolService
                                .getChannel(ctx.channel().id())
                                .orElseThrow(() -> new ShakeHandException("会话通道获取失败"));
                channelPoolService.addUserChannel(identify, channel);
                // 因为有可能携带了参数，导致客户端一直无法返回握手包，因此在校验通过后，重置请求路径
                request.setUri(properties.getPath());
            });
        }, () -> {
            log.error("ws请求不合法");
            ctx.close();
        });
    }
}
