package com.ruoyi.ibs.websocket;

import lombok.extern.slf4j.Slf4j;
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.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.util.concurrent.ConcurrentHashMap;

@ServerEndpoint("/task/websocket/{userName}")
@Component
@Slf4j
public class TaskWebSocket {

    private static final ConcurrentHashMap<String, Session> SESSION_MAP = new ConcurrentHashMap<>();

    @OnOpen
    public void onOpen(Session session, @PathParam("userName") String userName) {
        SESSION_MAP.put(userName, session);
        log.info("用户{}websocket连接成功", userName);
    }

    @OnClose
    public void onClose(@PathParam("userName") String userName) {
        SESSION_MAP.remove(userName);
        log.info("用户{}websocket连接关闭", userName);
    }

    @OnError
    public void onError(Session session, Throwable error) {
        error.printStackTrace();
    }

    public static void sendMessage(String userName, String message) {
        Session session = SESSION_MAP.get(userName);
        if (session != null && session.isOpen()) {
            session.getAsyncRemote().sendText(message);
        }
    }

}
