/**
 * Copyright &copy; 2015-2020 <a href="http://www.jeeplus.org/">JeePlus</a> All rights reserved.
 */
package com.jeeplus.common.websocket.onchat;

import java.util.*;

import org.java_websocket.WebSocket;


public class ChatServerPool {

	private static final Map<WebSocket,String> userconnections = new HashMap<WebSocket,String>();
	
	/**
	 * 获取用户名
	 * @param conn
	 */
	public static String getUserByKey(WebSocket conn){
		return userconnections.get(conn);
	}
	
	/**
	 * 获取WebSocket
	 * @param user
	 */
	public static List<WebSocket> getWebSocketByUser(String user){
		Set<WebSocket> keySet = userconnections.keySet();
		List<WebSocket> set = new ArrayList<>();
		synchronized (keySet) {
			for (WebSocket conn : keySet) {
				String cuser = userconnections.get(conn);
				if(cuser.equals(user)){
					set.add(conn);
				}
			}
		}
		return set;
	}
	
	/**
	 * 向连接池中添加连接
	 * @param conn
	 */
	public static void addUser(String user, WebSocket conn){
		userconnections.put(conn,user);	//添加连接
	}
	
	/**
	 * 获取所有的在线用户
	 * @return
	 */
	public static Collection<String> getOnlineUser(){
//		List<String> setUsers = new ArrayList<String>();
		Collection<String> setUsers = userconnections.values();
//		for(String u:setUser){
//			setUsers.add("<a onclick=\"toUserMsg('"+u+"');\">"+u+"</a>");
//		}
		return setUsers;
	}
	
	/**
	 * 移除连接池中的连接
	 * @param conn
	 */
	public static boolean removeUser(WebSocket conn){
		if(userconnections.containsKey(conn)){
			userconnections.remove(conn);	//移除连接
			return true;
		}else{
			return false;
		}
	}
	
	/**
	 * 向特定的用户发送数据
	 * @param message
	 * @param message
	 */
	public static void sendMessageToUser(WebSocket conn,String message){
		try {
			if(null != conn && null != userconnections.get(conn)){
				conn.send(message);
			}
		}catch (Exception e){
			System.out.println("sendMessageToUser Exception e:"+e);
			return;
		}
	}
	
	/**
	 * 向所有的用户发送消息
	 * @param message
	 */
	public static void sendMessage(String message){

			Set<WebSocket> keySet = userconnections.keySet();
			synchronized (keySet) {
				for (WebSocket conn : keySet) {
					String user = userconnections.get(conn);
					try {
						if(user != null){
							conn.send(message);
						}
					}catch (Exception e){
						System.out.println("sendMessage Exception e:"+e);
					}
				}
			}

	}
	/**
	 * 向所有的用户发送消息
	 */
	public static Boolean removeByUserId(String userId){
		try {
			boolean b = false;
			Set<WebSocket> keySet = userconnections.keySet();
			synchronized (keySet) {
				for (WebSocket conn : keySet) {
					String user = userconnections.get(conn);
					if(user != null && userId.equals(user)){
						b = ChatServerPool.removeUser(conn);
					}
				}
			}
			return b;
		}catch (Exception e){
			System.out.println("removeByUserId Exception e:"+e);
			return false;
		}

	}
}
