package com.ruoyi.framework.websocket;

import jakarta.websocket.CloseReason;
import jakarta.websocket.Session;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.util.List;
import java.util.Map;

/**
 * WebSocket 通用工具
 *
 * @author lwm
 */
public final class WebSocketUtils
{
    private static final Logger log = LoggerFactory.getLogger(WebSocketUtils.class);

    private WebSocketUtils()
    {
    }

    /**
     * 读取 URL 查询参数（取第一个值）
     */
    public static String resolveQueryParam(Session session, String name)
    {
        Map<String, List<String>> params = session.getRequestParameterMap();
        if (params == null || !params.containsKey(name))
        {
            return null;
        }
        List<String> values = params.get(name);
        return values == null || values.isEmpty() ? null : values.get(0);
    }

    /**
     * 关闭连接
     */
    public static void closeQuietly(Session session, CloseReason.CloseCode code, String reason)
    {
        if (session == null || !session.isOpen())
        {
            return;
        }
        try
        {
            session.close(new CloseReason(code, reason));
        }
        catch (IOException e)
        {
            log.info("关闭 WebSocket 失败: {}", e.getMessage());
        }
    }

}
