package com.zsc.edu.gateway.framework.websocket;

import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;

import java.io.IOException;
import java.util.Set;
import java.util.concurrent.CopyOnWriteArraySet;

public abstract class BaseWebSocketHandler extends TextWebSocketHandler {
    private final Set<WebSocketSession> sessions = new CopyOnWriteArraySet<>();

    @Override
    public void afterConnectionEstablished(WebSocketSession session) {
        sessions.add(session);
    }

    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus status) {
        sessions.remove(session);
    }

    public void broadcast(String message) {
        sessions.removeIf(session -> {
            if (!session.isOpen()) return true;
            try {
                session.sendMessage(new TextMessage(message));
            } catch (IOException e) {
                // 生产环境应使用日志记录
                e.printStackTrace();
            }
            return false;
        });
    }
}

class DeviceWebSocketHandler extends BaseWebSocketHandler {
}

class ProductWebSocketHandler extends BaseWebSocketHandler {
}

class RecordWebSocketHandler extends BaseWebSocketHandler {
}