package com.ltgk.boat.handler;


import com.alibaba.fastjson2.JSON;
import com.ltgk.boat.config.websocket.WebSocketSessionMap;
import com.ltgk.boat.service.ITrackWebsocketService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.AbstractWebSocketHandler;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.Map;

/**
 * 轨迹接续websocket
 *
 * @author Qi ChengBin
 * @date 2025/07/04
 */
@Slf4j
@Component
public class TrackWebsocketHandler extends AbstractWebSocketHandler {

    @Resource
    private ITrackWebsocketService trackWebsocketService;

    private final Map<String, WebSocketSession> webSocketSessionMap = new WebSocketSessionMap().sharedMap();

    /**
     * websocket 连接
     *
     * @param session:
     * @author Qi ChengBin
     * @date 2025/3/12
     */
    @Override
    public void afterConnectionEstablished(WebSocketSession session) {
        log.info("轨迹接续websocket连接成功，接收到session：{}", session);
        trackWebsocketService.saveWebsocketSession(session);
    }

    /**
     * websocket 接收数据
     *
     * @param session:
     * @param message:
     * @author Qi ChengBin
     * @date 2025/3/12
     */
    @Override
    protected void handleTextMessage(WebSocketSession session, TextMessage message) throws IOException {
        log.info("轨迹接续websocket接收到消息：{}", message);
        log.info("轨迹接续websocket接收到message：{}", JSON.toJSON(message.getPayload()));
        trackWebsocketService.pushTrackData(session);
    }

    /**
     * 监控断开链接 删除redis缓存
     *
     * @param session:
     * @param closeStatus:
     */
    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus closeStatus) {
        log.info("轨迹接续websocket断开链接，接收到session：{}", session);
        // 删除 session 对象
        if (this.webSocketSessionMap.containsKey(session.getId())) {
            this.webSocketSessionMap.remove(session.getId());
        }
    }
}
