package cn.sikey.websocket.websocket;

import cn.hutool.json.JSONUtil;
import cn.sikey.websocket.config.CacheConnectionStateManager;
import cn.sikey.websocket.util.ConnectionConverterUtil;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.web.socket.PongMessage;
import org.springframework.web.socket.WebSocketSession;

import java.io.IOException;

/**
 * @Author: nelson
 * @Date: 2025/5/29
 * @Description: 心跳
 */
@Slf4j
@Service
public class ConnectionHeartbeatService {

    @Resource
    private CacheConnectionStateManager cacheConnectionStateManager;

    /**
     * 自定义消息处理
     *
     * @param session 会话
     */
    public void handleCustomizedMessage(WebSocketSession session) {
        log.info("Refresh heartbeat after receiving message: {}", session);

        Connection connection = ConnectionConverterUtil.to(session);
        try {
            cacheConnectionStateManager.heartbeat(connection);
        } catch (Exception e) {
            log.error("There was a problem processing the heartbeat message", e);
            cacheConnectionStateManager.offline(connection);
        }
    }


    /**
     * 处理Pong消息
     *
     * @param session     会话
     * @param pongMessage pongMessage
     * @throws IOException 异常
     */
    public void handlePongMessage(WebSocketSession session, PongMessage pongMessage) throws IOException {
        log.debug("Received PONG from {}，pongMessage消息：{}", session.getId(), JSONUtil.toJsonPrettyStr(pongMessage));
    }

}
