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/9/3
 */
@Component
@ServerEndpoint(value = "/qxsd/realTimeEvent1")
public class RealTimeEventWs1 extends AbstractRealTimeEventWs {
    Logger logger = LoggerFactory.getLogger(RealTimeVehicleWs1.class);

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

    @Value("${qxsd.tunnel.down-id}")
    private String tunnelDownId;


    /**
     * 建立连接
     * @param session
     */
    @OnOpen
    public void onOpen(Session session){
        session.setMaxIdleTimeout(60000);
        sessionList.add(session);
        logger.info("ws建立连接-realTimeEvent1,当前连接数:{}",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.tunnelDownId;
    }

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