package com.xindazhou.message.config;

import com.corundumstudio.socketio.AckRequest;
import com.corundumstudio.socketio.SocketIOClient;
import com.corundumstudio.socketio.SocketIOServer;
import com.xindazhou.message.event.VehicleControlEventHandler;
import java.util.Map;
import jakarta.annotation.PostConstruct;
import jakarta.annotation.PreDestroy;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

/**
 * SocketIO Server 生命周期管理
 *
 * @author xindazhou
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class SocketIOServerLifecycle {

    private final SocketIOServer socketIOServer;
    private final VehicleControlEventHandler vehicleControlEventHandler;

    @PostConstruct
    public void startServer() {
        try {
            // 手动注册事件监听器（因为 @OnConnect 注解需要手动注册）
            // 注意：必须在 start() 之前注册监听器
            
            // 注册连接和断开连接监听器
            socketIOServer.addConnectListener(vehicleControlEventHandler::onConnect);
            socketIOServer.addDisconnectListener(vehicleControlEventHandler::onDisconnect);
            
            // 注册自定义事件监听器（vehicle_control 和 ping）
            socketIOServer.addEventListener("vehicle_control", Map.class, 
                (client, data, ackRequest) -> {
                    vehicleControlEventHandler.onVehicleControl(client, data, ackRequest);
                });
            socketIOServer.addEventListener("ping", String.class, 
                (client, data, ackRequest) -> {
                    vehicleControlEventHandler.onPing(client, ackRequest);
                });
            
            log.info("SocketIO 事件监听器注册完成");
            
            socketIOServer.start();
            log.info("SocketIO Server 启动成功");
        } catch (Exception e) {
            log.error("SocketIO Server 启动失败", e);
            throw new RuntimeException("SocketIO Server 启动失败", e);
        }
    }

    @PreDestroy
    public void stopServer() {
        try {
            socketIOServer.stop();
            log.info("SocketIO Server 停止成功");
        } catch (Exception e) {
            log.error("SocketIO Server 停止失败", e);
        }
    }

}

