package com.business.socket;


import com.business.socket.bean.PushModel;

import javax.websocket.Session;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;

/******************************
 * TODO
 * @author yanhongliang
 * @date 2021-03-21 06:13
 ******************************/

public class WebSocketServerPool {

    // 用户连接池
    private static final ConcurrentHashMap<Session, String> userConnections = new ConcurrentHashMap<Session, String>();

    /**
     * 获取用户名
     */
    public static String getUserByKey(Session session){
        return userConnections.get(session);
    }

    /**
     * 获取WebSocket
     */
    public static Session getWebSocketByUser(String user){
        Set<Session> keySet = userConnections.keySet();
        synchronized (keySet) {
            for (Session session : keySet) {
                String cuser = userConnections.get(session);
                if(cuser.equals(user)){
                    return session;
                }
            }
        }
        return null;
    }

    /**
     * 向连接池中添加连接
     */
    public static void addUser(Session session, String user){
        userConnections.put(session,user);	//添加连接
    }

    /**
     * 获取所有的在线用户
     */
    public static Collection<String> getOnlineUser(){
        List<String> setUsers = new ArrayList<String>();
        Collection<String> setUser = userConnections.values();
        for(String u:setUser){
            setUsers.add(u);
        }
        return setUsers;
    }

    /**
     * 移除连接池中的连接
     */
    public static boolean removeUser(Session session){
        if(userConnections.containsKey(session)){
            userConnections.remove(session);	//移除连接
            return true;
        }else{
            return false;
        }
    }

    /**
     * 向特定的用户发送数据
     * @param users 目标用户登录名集合
     * @param pushModel 消息体
     */
    public static void sendMessageToUser(Set<String> users, PushModel pushModel){
        for (String user : users) {
            Session session = getWebSocketByUser(user);
            if (session != null) {
                MessageManager.add(session, pushModel);
            }
        }
        MessageManager.submit();
    }

    /**
     * 向所有的用户发送消息
     */
    public static void sendMessage(PushModel pushModel){
        Set<Session> keySet = userConnections.keySet();
        synchronized (keySet) {
            for (Session session : keySet) {
                String user = userConnections.get(session);
                if(user != null){
                    MessageManager.add(session, pushModel);
                }
            }
            MessageManager.submit();
        }
    }

}
