package com.cico.nest.lcdp.boot.core.qxsd.adapter.ws;

import jakarta.websocket.OnClose;
import jakarta.websocket.OnError;
import jakarta.websocket.OnOpen;
import jakarta.websocket.Session;
import jakarta.websocket.server.ServerEndpoint;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;

/**
 * 上行洞的实时事件
 * @author zws
 * @date 2024/8/14
 */

@Component
@ServerEndpoint(value = "/qxsd/realTimeEvent")
public class RealTimeEventWs extends AbstractRealTimeEventWs {

    @Value("${qxsd.tunnel.up-id}")
    private String tunnelUpId;
    Logger logger = LoggerFactory.getLogger(RealTimeVehicleWs.class);

    private final static List<Session> sessionList = new CopyOnWriteArrayList<>();


    /**
     * 建立连接
     * @param session
     */
    @OnOpen
    public void onOpen(Session session){
        session.setMaxIdleTimeout(60000);
        sessionList.add(session);
        logger.info("ws建立连接-realTimeEvent,当前连接数:{}",sessionList.size());
    }

    /**
     * 发生错误
     * @param session
     * @param error
     */
    @OnError
    public void onError(Session session, Throwable error) {
        logger.info("服务端发生了错误"+error.getMessage());
    }

    /**
     * 关闭连接
     */
    @OnClose
    public void onClose(Session session) {
        sessionList.remove(session);
    }

    @Override
    public String tunnelId() {
        return this.tunnelUpId;
    }

    /**
     * 推送消息
     * @param message
     */
    @Override
    public void sendMessage(String message) {
        for (Session session : sessionList) {
            try {
                session.getBasicRemote().sendText(message);
            } catch (Exception e) {
                logger.info("服务端发送消息失败"+e.getMessage());
            }
        }
    }

}
