package com.ssyf.ws.interceptor;

import com.ssyf.ws.constants.WebSocketConstants;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.server.HandshakeInterceptor;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.HashMap;
import java.util.Map;

/**
 * WebSocket认证拦截器
 * 处理WebSocket连接建立前的认证逻辑
 */
@Slf4j
@Component
public class WebSocketAuthInterceptor implements HandshakeInterceptor {

    @Override
    public boolean beforeHandshake(ServerHttpRequest servletRequest, ServerHttpResponse servletResponse, WebSocketHandler wsHandler, Map<String, Object> attributes) throws Exception {
        // 解析查询字符串，设置 session参数
        String queryString = servletRequest.getURI().getQuery();
        if (queryString != null) {
            Map<String, String> queryParams = parseQueryString(queryString);
            attributes.putAll(queryParams);
        }
        log.info(attributes.toString());
        return true;
    }


    @Override
    public void afterHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler, Exception exception) {
        // 可以在这里访问之前存储的属性
        //System.out.println("WebSocketHandshakeInterceptor.afterHandshake");
    }

    private Map<String, String> parseQueryString(String queryString) throws UnsupportedEncodingException {
        Map<String, String> queryParams = new HashMap<>();
        String[] pairs = queryString.split("&");
        for (String pair : pairs) {
            int idx = pair.indexOf("=");
            if (idx > 0) {
                String key = URLDecoder.decode(pair.substring(0, idx), "UTF-8");
                String value = URLDecoder.decode(pair.substring(idx + 1), "UTF-8");
                queryParams.put(key, value);
            }
        }
        return queryParams;
    }
}