package com.ruoyi.framework.websocket;

import java.io.IOException;
import java.util.Collection;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import javax.websocket.Session;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * websocket 客户端用户集
 * 
 * @author ruoyi
 */
public class WebSocketUsers {
    private static final Logger LOGGER = LoggerFactory.getLogger(WebSocketUsers.class);

    // 保存用户ID和Session的映射
    private static final Map<String, Session> USER_SESSIONS = new ConcurrentHashMap<>();
    // 保存Session和用户ID的映射
    private static final Map<String, String> SESSION_USERS = new ConcurrentHashMap<>();

    public static void put(String userId, Session session) {
        // 如果该用户已经有连接，先关闭旧连接
        Session oldSession = USER_SESSIONS.get(userId);
        if (oldSession != null && oldSession.isOpen()) {
            try {
                sendMessageToUserByText(oldSession, "您的账号在其他地方登录，当前连接将被关闭");
                oldSession.close();
            } catch (IOException e) {
                LOGGER.error("关闭旧连接失败", e);
            }
        }

        // 保存新连接
        USER_SESSIONS.put(userId, session);
        SESSION_USERS.put(session.getId(), userId);
        LOGGER.info("用户[{}]建立新连接", userId);
    }

    public static void remove(Session session) {
        String userId = SESSION_USERS.remove(session.getId());
        if (userId != null) {
            USER_SESSIONS.remove(userId);
            LOGGER.info("用户[{}]断开连接", userId);
        }
    }

    public static Session getSession(String userId) {
        return USER_SESSIONS.get(userId);
    }

    public static String getUserId(Session session) {
        return SESSION_USERS.get(session.getId());
    }

    public static void sendMessageToUserByText(Session session, String message) {
        try {
            session.getBasicRemote().sendText(message);
        } catch (IOException e) {
            LOGGER.error("发送消息失败", e);
        }
    }

    public static void broadcastLocation(String message) {
        USER_SESSIONS.values().forEach(session -> {
            sendMessageToUserByText(session, message);
        });
    }

    public static int getOnlineCount() {
        return USER_SESSIONS.size();
    }
}
