package com.ruoyi.platform.webSocket;

import javax.annotation.Resource;
import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;

import com.ruoyi.platform.service.ExperimentInsService;
import com.ruoyi.platform.utils.K8sClientUtil;
import org.springframework.stereotype.Component;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.RestController;

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

@Component
@Slf4j
@ServerEndpoint("/websocket/workflowLogs")
@RestController
public class WebSocket {
    private Session session;
    private String userId;
    private static CopyOnWriteArraySet<WebSocket> webSockets = new CopyOnWriteArraySet<>();
    private static ConcurrentHashMap<String, Session> sessionPool = new ConcurrentHashMap<>();

    @OnOpen
    public void onOpen(Session session, @PathParam("userId") String userId) {
        try {
            this.session = session;
            this.userId = "workflowLogs";
            webSockets.add(this);
            sessionPool.put(userId, session);
            log.info("【WebSocket 消息】有新的连接，总数为：" + webSockets.size());
        } catch (Exception e) {
            // 异常处理
        }
    }

    @OnClose
    public void onClose() {
        try {
            webSockets.remove(this);
            sessionPool.remove(this.userId);
            log.info("【WebSocket 消息】连接断开，总数为：" + webSockets.size());
        } catch (Exception e) {
            // 异常处理
        }
    }

    @OnMessage
    public void onMessage(String message, Session session) {
        log.info("【WebSocket 消息】收到客户端消息：" + message);
        // 处理收到的消息，例如获取实时日志数据

        // 推送日志数据给客户端
        try {
            session.getBasicRemote().sendText("nihao");
        } catch (Exception e) {
            log.error("【WebSocket 消息】推送日志数据失败：" + e.getMessage());
        }
    }

    @OnError
    public void onError(Session session, Throwable error) {
        log.error("【WebSocket 消息】发生错误：" + error.getMessage());
    }
}
