package com.inspect.base.websocket.configure;

import com.inspect.base.websocket.domain.WebSocketMessage;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.java_websocket.WebSocket;

public class WsPool {
   private static Map<WebSocket, String> wsUserMap = new HashMap();

   public static String getUserByWs(WebSocket conn) {
      return (String)wsUserMap.get(conn);
   }

   public static WebSocket getWsByUser(String userName) {
      Set<WebSocket> keySet = wsUserMap.keySet();
      synchronized(keySet) {
         Iterator var3 = keySet.iterator();

         WebSocket conn;
         String cuser;
         do {
            if (!var3.hasNext()) {
               return null;
            }

            conn = (WebSocket)var3.next();
            cuser = (String)wsUserMap.get(conn);
         } while(!cuser.equals(userName));

         return conn;
      }
   }

   public static void addUser(String userName, WebSocket conn) {
      wsUserMap.put(conn, userName);
   }

   public static Collection<String> getOnlineUser() {
      List<String> setUsers = new ArrayList();
      Collection<String> setUser = wsUserMap.values();
      Iterator var2 = setUser.iterator();

      while(var2.hasNext()) {
         String u = (String)var2.next();
         setUsers.add(u);
      }

      return setUsers;
   }

   public static boolean removeUser(WebSocket conn) {
      if (wsUserMap.containsKey(conn)) {
         wsUserMap.remove(conn);
         return true;
      } else {
         return false;
      }
   }

   public static void sendMessageToUser(WebSocket conn, String message) {
      if (null != conn && null != wsUserMap.get(conn)) {
         conn.send(message);
      }

   }

   public static void sendMessageToAll(String message) {
      Set<WebSocket> keySet = wsUserMap.keySet();
      synchronized(keySet) {
         Iterator var3 = keySet.iterator();

         while(var3.hasNext()) {
            WebSocket conn = (WebSocket)var3.next();
            String user = (String)wsUserMap.get(conn);
            if (user != null) {
               if ((new Date()).getTime() / 100000L % 10L == 0L) {
                  System.out.println("WebSocket conn user = " + user);
               }

               conn.send(message);
            }
         }

      }
   }

   public static void main(String[] args) throws InterruptedException {
      while(true) {
         System.out.println((new Date()).getTime());
         Thread.sleep(1000L);
      }
   }

   public static void sendMessageToAll(WebSocketMessage webSocketMessage) {
      sendMessageToAll(webSocketMessage.toString());
   }
}
