package org.matrix.socket;

import org.springframework.web.socket.WebSocketSession;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author huangxiahao
 */
public class ExecuteMonitorSocketPool {

    private static final ConcurrentHashMap<String, List<WebSocketSession>> SOCKET_MAP = new ConcurrentHashMap<>();

    private static final ConcurrentHashMap<String, List<String>> SOCKET_KEY_MAP = new ConcurrentHashMap<>();

    public static void add(String key,WebSocketSession clientSocket){
        if (clientSocket != null &key !=null) {
            List<WebSocketSession> webSocketSessions = SOCKET_MAP.get(key);
            if (webSocketSessions!=null){
                webSocketSessions.add(clientSocket);
            }else {
                webSocketSessions = new ArrayList<>();
                webSocketSessions.add(clientSocket);
                SOCKET_MAP.put(key,webSocketSessions);
            }
            addKeyMap(clientSocket.getId(),key);
        }
    }

    public static void addKeyMap(String socketId,String key){
        if (socketId != null &key !=null) {
            List<String> list = SOCKET_KEY_MAP.get(socketId);
            if (list!=null){
                list.add(key);
            }else {
                list = new ArrayList<>();
                list.add(key);
                SOCKET_KEY_MAP.put(socketId,list);
            }
        }
    }

    public static void remove(WebSocketSession clientSocket){
        List<String> list = SOCKET_KEY_MAP.get(clientSocket.getId());
        if (list!=null){
            for (String s : list) {
                SOCKET_MAP.get(s).remove(clientSocket);
            }
        }

    }



    public static List<WebSocketSession> get(String key){
       return SOCKET_MAP.get(key);
    }
}