package com.huimv.env.input.ws;

import com.alibaba.fastjson.JSON;
import org.springframework.util.ObjectUtils;

import javax.websocket.RemoteEndpoint;
import javax.websocket.Session;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class WebsocketWorkerUtil {
  /**
   * 记录当前在线的Session
   */
  private static final Map<Integer, List<Session>> SESSIONS = new ConcurrentHashMap<>();



  /**
   * 添加session
   * @param userId
   * @param session
   */

  public static void addSession(Integer userId, Session session){
    // 此处只允许一个用户的session链接。一个用户的多个连接，我们视为无效。
    List<Session> sessions = SESSIONS.get(userId);
    if (sessions == null){
      sessions = new ArrayList<Session>();
    }
    sessions.add(session);
    SESSIONS.putIfAbsent ( userId, sessions );
  }

  /**
   * 关闭session
   * @param userId
   */
  public static void removeSession(Integer userId){
    synchronized (SESSIONS){
      List<Session> sessions = SESSIONS.get(userId);
      if(sessions == null){
        return;
      }
      List<Integer> list  = new ArrayList<>();

      for (int i = 0; i < sessions.size(); i++) {
        Session session = sessions.get(i);
        try {
          if (session.isOpen()) {

          } else {
            list.add(i);
          }
        } catch (Exception e) {
          e.printStackTrace();
          sessions.remove(session);
        }
      }
      for (int i : list) {
        sessions.remove(i);
      }

    }

    //集合不能全部清空
//    SESSIONS.remove ( userId );
  }


  public static void sendMessage(Session session, String msg){
    if(session == null){
      return;
    }

    // 同步
    RemoteEndpoint.Async async = session.getAsyncRemote ();
    async.sendText (msg);
  }

  public synchronized static void sendWarningMessage(Integer farmId ,String msg){
    synchronized (SESSIONS){
      List<Session> sessions = SESSIONS.get(farmId);
      if(sessions == null){
        return;
      }
      List<Integer> list  = new ArrayList<>();

      for (int i = 0; i < sessions.size(); i++) {
        Session session = sessions.get(i);
        try {
          if (session.isOpen()) {
            session.getBasicRemote().sendText(msg);
          } else {
            list.add(i);
          }
        } catch (Exception e) {
          e.printStackTrace();
          sessions.remove(session);
        }
      }
      for (int i : list) {
        sessions.remove(i);
      }

    }

  }


}
