package com.ssyf.ws.utils;

import com.ssyf.ws.constants.WebSocketConstants;
import com.ssyf.ws.domain.SessionInfo;
import org.springframework.web.socket.WebSocketSession;

/**
 * WebSocket工具类
 */
public class WebSocketUtils {

    /**
     * 从WebSocketSession中获取用户ID
     */
    public static String getUserId(WebSocketSession session) {
        return (String) session.getAttributes().get(WebSocketConstants.SESSION_ATTR_USER_ID);
    }

    /**
     * 从WebSocketSession中获取用户名
     */
    public static String getUsername(WebSocketSession session) {
        return (String) session.getAttributes().get(WebSocketConstants.SESSION_ATTR_USERNAME);
    }

    /**
     * 检查会话是否已认证
     */
    public static boolean isAuthenticated(WebSocketSession session) {
        Boolean authenticated = (Boolean) session.getAttributes().get(WebSocketConstants.SESSION_ATTR_AUTHENTICATED);
        return authenticated != null && authenticated;
    }

    /**
     * 构建会话信息
     */
    public static SessionInfo buildSessionInfo(WebSocketSession session) {
        String userId = getUserId(session);
        String username = getUsername(session);
        String sessionId = session.getId();

        SessionInfo sessionInfo = new SessionInfo(userId, username, sessionId);
        sessionInfo.setClientInfo(session.getRemoteAddress().toString());
        sessionInfo.setLoginTime((Long) session.getAttributes().get(WebSocketConstants.SESSION_ATTR_LOGIN_TIME));

        return sessionInfo;
    }
}