package cn.reghao.tnb.search.esapp.ws;

import cn.reghao.jutil.jdk.serializer.JdkSerializer;
import cn.reghao.jutil.jdk.serializer.JsonConverter;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.BinaryMessage;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * @author reghao
 * @date 2023-03-01 11:03:31
 */
@Component
public class WsSender {
    private final static Map<String, WebSocketSession> sessionMap = new HashMap<>();

    public void addSession(String machineId, WebSocketSession session) {
        sessionMap.put(machineId, session);
    }

    public void removeSession(String machineId) {
        sessionMap.remove(machineId);
    }

    public void send(String dest, Object message) throws IOException {
        WebSocketSession session = sessionMap.get(dest);
        if (session != null) {
            byte[] bytes = JdkSerializer.serialize(message);
            BinaryMessage binaryMessage = new BinaryMessage(bytes);
            session.sendMessage(binaryMessage);
        }
    }

    public void sendMessage(String dest, Object message) throws IOException {
        WebSocketSession session = sessionMap.get(dest);
        if (session != null) {
            String json = JsonConverter.objectToJson(message);
            TextMessage textMessage = new TextMessage(json);
            session.sendMessage(textMessage);
        }
    }
}
