package com.xinda.framework.websocket;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.atomic.AtomicInteger;

@Component
@ServerEndpoint("/ws/alert/{deptId}")
public class WebSocketAlertServer {
    private static final Logger log = LoggerFactory.getLogger(WebSocketAlertServer.class);

    //静态变量，用来记录当前在线连接数。应该把它设计成线程安全的。
    private static AtomicInteger onlineNum = new AtomicInteger();

    //concurrent包的线程安全Set，用来存放每个客户端对应的WebSocketServer对象。
    private static ConcurrentHashMap<Long, Session> sessionPools = new ConcurrentHashMap<>();

    /**
     * 线程安全list，用来存放 在线客户端账号
     */
    public static List<Long> deptList = new CopyOnWriteArrayList<>();


    /**
     * 连接成功
     * @param session
     * @param deptId
     */
    @OnOpen
    public void onOpen(Session session, @PathParam(value = "deptId") Long deptId) {
        sessionPools.put(deptId, session);
        if (!deptList.contains(deptId)) {
            addOnlineCount();
            deptList.add(deptId);
        }
        log.debug("ID为【" + deptId + "】的用户加入websocket！当前在线人数为：" + onlineNum);
        log.debug("当前在线：" + deptList);
    }

    /**
     * 关闭连接
     * @param deptId
     */
    @OnClose
    public void onClose(@PathParam(value = "deptId") Long deptId) {
        sessionPools.remove(deptId);
        if (deptList.contains(deptId)) {
            deptList.remove(deptId);
            subOnlineCount();
        }
        log.debug(deptId + "断开webSocket连接！当前人数为" + onlineNum);

    }

    /**
     * 消息监听
     * @param message
     * @throws IOException
     */
    @OnMessage
    public void onMessage(String message) throws IOException {
        String msg = message.replace("你", "我").replace("吗", "");
//         sendToUser(userId, JSONObject.toJSONString(jsonObject));

    }

    /**
     * 连接错误
     * @param session
     * @param throwable
     * @throws IOException
     */
    @OnError
    public void onError(Session session, Throwable throwable) throws IOException {
        log.error("websocket连接错误！");
        throwable.printStackTrace();
    }

    /**
     * 发送消息
     */
    public void sendMessage(Session session, String message) throws IOException, EncodeException {
        if (session != null) {
            synchronized (session) {
                session.getBasicRemote().sendText(message);
            }
        }
    }

    /**
     * 给指定用户发送信息
     */
    public void sendToUser(Long deptId, String message) {
        Session session = sessionPools.get(deptId);
        try {
            if (session != null) {
                sendMessage(session, message);
            }else {
                log.debug("推送用户不在线");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void addOnlineCount() {
        onlineNum.incrementAndGet();
    }

    public static void subOnlineCount() {
        onlineNum.decrementAndGet();

    }
}