package com.huashe.park.application.socket.server;

import com.alibaba.fastjson2.JSON;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.CrossOrigin;

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

@ServerEndpoint("/pkbs/evt/{device}")
@CrossOrigin(origins = "*")
@Component
public class FenceVioEvtSocketServer {
    private static final Logger logger = LoggerFactory.getLogger(FenceVioEvtSocketServer.class);
    //静态变量，用来记录当前在线连接数。应该把它设计成线程安全的。
    private static AtomicInteger onlineNum = new AtomicInteger();
    //concurrent包的线程安全Set，用来存放每个客户端对应的WebSocketServer对象。
    private static ConcurrentHashMap<String, Session> sessionPools = new ConcurrentHashMap<>();

    @PostConstruct
    public void init() {
        logger.info("WebSocketServer init");
    }

    //发送消息
    public void sendMessage(Session session, String message) throws IOException {
        if (session != null) {
            synchronized (session) {
                logger.info("发送数据：{}", message);
                session.getBasicRemote().sendText(message);
            }
        }
    }

    //给指定用户发送信息
    public void sendInfo(String userName, String message) {
        Session session = sessionPools.get(userName);
        if (session == null) return;
        try {
            sendMessage(session, message);
        } catch (Exception e) {
            logger.info("server get {}", e.getMessage());
        }
    }

    // 群发消息
    public void broadcast(Object message) {
        for (Session session : sessionPools.values()) {
            try {
                sendMessage(session, JSON.toJSONString(message));
            } catch (Exception e) {
                logger.info("server get {}", e.getMessage());
            }
        }
    }

    //建立连接成功调用
    @OnOpen
    public void onOpen(Session session, @PathParam(value = "device") String device) {
        sessionPools.put(device, session);
        addOnlineCount();
    }

    //关闭连接时调用
    @OnClose
    public void onClose(@PathParam(value = "device") String device) {
        sessionPools.remove(device);
        subOnlineCount();
        logger.info("{}断开webSocket连接！当前人数为:{}", device, onlineNum);
    }

    //收到客户端信息后，根据接收人的username把消息推下去或者群发
    // to=-1群发消息
    @OnMessage
    public void onMessage(String message) throws IOException {
        logger.info("server get {}", message);
    }

    //错误时调用
    @OnError
    public void onError(Session session, Throwable throwable) {
        logger.info("server get {}", throwable.getMessage());
    }

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

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

    public static AtomicInteger getOnlineNumber() {
        return onlineNum;
    }

    public static ConcurrentHashMap<String, Session> getSessionPools() {
        return sessionPools;
    }
}
