package com.zhentao.handler;

import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.http.server.ServletServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.server.HandshakeInterceptor;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

/**
 * WebSocket握手拦截器
 * 用于验证用户身份和传递参数
 */
@Component
public class WebSocketInterceptor implements HandshakeInterceptor {

    @Override
    public boolean beforeHandshake(ServerHttpRequest request, ServerHttpResponse response,
                                    WebSocketHandler wsHandler, Map<String, Object> attributes) throws Exception {
        
        if (request instanceof ServletServerHttpRequest) {
            ServletServerHttpRequest serverRequest = (ServletServerHttpRequest) request;
            HttpServletRequest servletRequest = serverRequest.getServletRequest();
            
            // 从请求参数中获取用户ID
            String userIdStr = servletRequest.getParameter("userId");
            
            if (userIdStr == null || userIdStr.isEmpty()) {
                System.err.println("WebSocket连接失败: 缺少userId参数");
                return false;
            }
            
            try {
                Long userId = Long.parseLong(userIdStr);
                // 将用户ID存入WebSocketSession attributes
                attributes.put("userId", userId);
                
                System.out.println("用户 " + userId + " 准备建立WebSocket连接");
                return true;
            } catch (NumberFormatException e) {
                System.err.println("WebSocket连接失败: userId格式错误");
                return false;
            }
        }
        
        return false;
    }

    @Override
    public void afterHandshake(ServerHttpRequest request, ServerHttpResponse response,
                                WebSocketHandler wsHandler, Exception exception) {
        if (exception != null) {
            System.err.println("WebSocket握手后异常: " + exception.getMessage());
        }
    }
}





