package com.cmvr.framework.websocket.manager;

import org.springframework.stereotype.Component;
import org.springframework.web.socket.WebSocketSession;

import java.util.Collections;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;

@Component
public class ChannelSubscriptionManager {

    // 频道 -> 连接集合
    private final Map<String, Set<WebSocketSession>> channelSessions = new ConcurrentHashMap<>();

    public void subscribe(String channel, WebSocketSession session) {
        channelSessions.computeIfAbsent(channel, k -> ConcurrentHashMap.newKeySet()).add(session);
    }

    public void unsubscribe(String channel, WebSocketSession session) {
        Set<WebSocketSession> sessions = channelSessions.get(channel);
        if (sessions != null) {
            sessions.remove(session);
            if (sessions.isEmpty()) {
                channelSessions.remove(channel);
            }
        }
    }

    public Set<WebSocketSession> getSubscribedSessions(String channel) {
        return channelSessions.getOrDefault(channel, Collections.emptySet());
    }

    public boolean hasSubscribers(String channel) {
        return channelSessions.containsKey(channel);
    }

    public void clearSession(WebSocketSession session) {
        channelSessions.keySet().forEach(channel -> unsubscribe(channel, session));
    }

}