package cn.reghao.tnb.message.app.ws.device;

import cn.reghao.jutil.jdk.serializer.JsonConverter;
import cn.reghao.tnb.message.api.model.EventType;
import cn.reghao.tnb.message.api.model.resp.EventMessageResp;
import cn.reghao.tnb.message.app.rabbit.RabbitProducer;
import cn.reghao.tnb.message.app.redis.ds.RedisHash;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;

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

/**
 * @author reghao
 * @date 2025-10-12 14:53:07
 */
@Slf4j
@Service
public class DeviceService {
    // sessionId -> deviceId
    private final Map<String, String> sessionDevices = new HashMap<>();

    public DeviceService(RabbitProducer rabbitProducer, RedisHash<HashSet<Long>> redisHash) {
    }

    public boolean addSession(WebSocketSession webSocketSession) {
        String sessionId = webSocketSession.getId();
        String deviceId = (String) webSocketSession.getAttributes().get("deviceId");
        sessionDevices.put(sessionId, deviceId);
        log.info("device {} connected", deviceId);
        return true;
    }

    public void removeSession(WebSocketSession webSocketSession) {
        String sessionId = webSocketSession.getId();
        String deviceId = sessionDevices.get(sessionId);
        sessionDevices.remove(sessionId);
        log.info("device {} connected", deviceId);
    }

    public void sendHeartbeatPong(WebSocketSession session) throws IOException {
        EventMessageResp<String> resp = new EventMessageResp<>(EventType.heartbeat, "pong");
        TextMessage textMessage = new TextMessage(JsonConverter.objectToJson(resp));
        session.sendMessage(textMessage);
    }
}
