package com.pwt.netty.handler;

import cn.hutool.core.map.MapUtil;
import com.pwt.common.constant.Constants;
import com.pwt.common.core.domain.model.LoginUser;
import com.pwt.common.enums.SeparatorEnum;
import com.pwt.common.utils.CacheMap;
import com.pwt.common.utils.StringUtils;
import com.pwt.common.utils.spring.SpringUtils;
import com.pwt.framework.web.service.TokenService;
import com.pwt.netty.conponents.SocketParser;
import io.jsonwebtoken.Claims;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.FullHttpRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.Map;

/**
 * @author linyun
 * @version V1.0
 * @Title: WebSocketSecurityHandler
 * @Description: 站控系统安全认证处理类
 * @date 2022/11/11
 **/
@Slf4j
@Component
public class WebSocketSecurityHandler extends SimpleChannelInboundHandler<FullHttpRequest> {

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, FullHttpRequest request) throws Exception
    {
        // 解析客户端的带上来的queryString websocket连接字符串：ws://127.0.0.1:3000/websocket?token=0123456789ABCDEFG
        // 客户端连接字符串由服务端业务接口下发
        Map<String, String> paramMap = getUrlParams(request.uri());
        String token = paramMap.get("token");
        log.info("client token:{}", token);
        if (StringUtils.isBlank(token))
        {
            ctx.close();
            log.info("token为空,断开连接");
            return;
        }
        LoginUser loginUser = getUserByToken(token);
        // token校验逻辑:
        if (!StringUtils.isNull(loginUser))
        {
            // 校验通过后,保存通道
            Long userId = loginUser.getUserId();
            request.setUri(SocketParser.WEBSOCKET_PATH);
            request.headers().set("userId", userId);
            // 校验通过之后，传递到下一个hander处理
            ctx.fireChannelRead(request.retain());
            // 只是首次校验，之后消息传递不需要权限校验
            ctx.pipeline().remove(this.getClass());
        } else
        {
            log.error("token校验不通过");
            ctx.close();
        }

    }


    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception
    {
        ctx.close();
        log.error(cause.getMessage());
    }


    private LoginUser getUserByToken(String token)
    {
        TokenService tokenService = SpringUtils.getBean(TokenService.class);
        Claims claims = tokenService.parseToken(token);
        String uuid = (String) claims.get(Constants.LOGIN_USER_KEY);
        //redis中是以userkey为键值存储
        String userKey = tokenService.getTokenKey(uuid);
        //根据键值userkey获取loginUser对象
        return (LoginUser) CacheMap.getCache(userKey);
    }

    /**
     * 将请求中的参数转为map
     **/
    private static Map<String, String> getUrlParams(String url)
    {
        Map<String, String> map = MapUtil.newHashMap(10);
        url = url.replace(SeparatorEnum.QUESTION.getCode(), SeparatorEnum.SEMICOLON.getCode());
        if (!url.contains(SeparatorEnum.SEMICOLON.getCode()))
        {
            return map;
        }
        if (url.split(SeparatorEnum.SEMICOLON.getCode()).length > 0)
        {
            String[] arr = url.split(SeparatorEnum.SEMICOLON.getCode())[1].split(SeparatorEnum.AND.getCode());
            for (String s : arr)
            {
                String key = s.split(SeparatorEnum.EQUALS.getCode())[0];
                String value = s.split(SeparatorEnum.EQUALS.getCode())[1];
                map.put(key, value);
            }
            return map;
        } else
        {
            return map;
        }
    }
}
