package com.qaup.collision.websocket.listener;

import com.qaup.collision.websocket.event.AircraftRouteUpdateEvent;
import com.qaup.collision.websocket.handler.CollisionWebSocketHandler;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Component;

/**
 * 航空器路由更新事件监听器
 * 
 * 监听航空器路由更新事件，并通过WebSocket推送给前端客户端
 * 
 * @author AI Assistant
 * @version 1.0
 * @since 2025-01-17
 */
@Slf4j
@Component
public class AircraftRouteUpdateEventListener {
    
    @Autowired
    private CollisionWebSocketHandler webSocketHandler;
    
    @Autowired
    private ObjectMapper objectMapper;
    
    /**
     * 处理航空器路由更新事件
     * 
     * @param event 航空器路由更新事件
     */
    @EventListener
    public void handleAircraftRouteUpdateEvent(AircraftRouteUpdateEvent event) {
        try {
            // 构建WebSocket消息
            String message = objectMapper.writeValueAsString(new WebSocketMessage(
                "aircraftRouteUpdate", 
                event, 
                System.currentTimeMillis()
            ));
            
            // 广播消息给所有连接的客户端
            webSocketHandler.broadcastMessage(message);
            
            log.info("航空器路由更新事件已通过WebSocket推送: 航班号={}, 路由类型={}, 状态={}", 
                    event.getFlightNo(), event.getRouteType(), event.getAircraftStatus());
            
        } catch (Exception e) {
            log.error("处理航空器路由更新事件失败: flightNo={}", event.getFlightNo(), e);
        }
    }
    
    /**
     * WebSocket消息包装类
     */
    private static class WebSocketMessage {
        public final String type;
        public final Object data;
        public final long timestamp;
        
        public WebSocketMessage(String type, Object data, long timestamp) {
            this.type = type;
            this.data = data;
            this.timestamp = timestamp;
        }
    }
}