package com.dcs.equipment.server;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.websocket.OnClose;
import javax.websocket.OnError;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.concurrent.CopyOnWriteArraySet;

/**
 * @author: wangpx
 * @date: 2025-03-06 16:18
 */

@Component
@ServerEndpoint(value = "/webSocket/equipment/list")
public class EquipmentListWebSocketServer {
    private static Logger log = LoggerFactory.getLogger(EquipmentListWebSocketServer.class);
    private static final CopyOnWriteArraySet<Session> sessionPools = new CopyOnWriteArraySet<>();

    /**
     * 有客户端连接成功
     */
    @OnOpen
    public void onOpen(Session session){
        sessionPools.add(session);
        log.info("新的 WebSocketList 客户端已连接");
    }

    /**
     * 连接关闭调用的方法
     */
    @OnClose
    public void onClose(Session session) {
        sessionPools.remove(session);
        log.info("WebSocketList 客户端已断开连接");
    }

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

    /**
     * 群发消息
     */
    public void broadCastInfo(String message) {
        for (Session session : sessionPools) {
            if (!session.isOpen()) {
                continue;
            }
            try {
                sendMessage(session, message);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 发生错误
     */
    @OnError
    public void onError(Session session, Throwable throwable){
        log.error("WebSocketList 发生错误");
        throwable.printStackTrace();
    }

}
