/**
 * Flash Detector Module - 光斑检测订阅模块
 * 通过 rosbridge_server 订阅光斑检测结果
 *
 * 订阅的话题:
 *   /flash_detector/flash_detected   (std_msgs/Bool) - 是否检测到光斑
 *   /flash_detector/detection       (std_msgs/Float32MultiArray) - [cx, cy, area, sight_x, sight_y]
 */

const FlashDetectorModule = (() => {
    let ros = null;
    let flashDetectedSub = null;
    let detectionSub = null;

    // 回调函数
    let onFlashDetected = null;
    let onDetectionData = null;

    // 检测状态
    let flashDetected = false;
    let detectionData = {
        cx: 0,
        cy: 0,
        area: 0,
        sightX: 0,
        sightY: 0
    };

    // 图像尺寸 (默认 640x480，需要根据实际相机调整)
    let imageWidth = 640;
    let imageHeight = 480;

    /**
     * 初始化模块
     * @param {ROSLIB.Ros} rosInstance - ROS 连接实例
     * @param {Object} callbacks - 回调函数对象
     *   - onFlashDetected: (detected: boolean) => void
     *   - onDetectionData: (data: DetectionData) => void
     */
    function init(rosInstance, callbacks = {}) {
        ros = rosInstance;
        onFlashDetected = callbacks.onFlashDetected || null;
        onDetectionData = callbacks.onDetectionData || null;

        // 设置图像尺寸 (可选)
        if (callbacks.imageWidth) imageWidth = callbacks.imageWidth;
        if (callbacks.imageHeight) imageHeight = callbacks.imageHeight;

        setupSubscriptions();

        console.log('[Flash Detector] 模块初始化完成');
        console.log('[Flash Detector] 订阅话题: /flash_detector/flash_detected');
        console.log('[Flash Detector] 订阅话题: /flash_detector/detection');
    }

    /**
     * 设置订阅
     */
    function setupSubscriptions() {
        // 订阅闪光检测标志
        flashDetectedSub = new ROSLIB.Topic({
            ros: ros,
            name: '/flash_detector/flash_detected',
            messageType: 'std_msgs/Bool'
        });

        flashDetectedSub.subscribe((msg) => {
            flashDetected = msg.data;

            if (onFlashDetected) {
                onFlashDetected(msg.data);
            }
        });

        // 订阅检测数据
        detectionSub = new ROSLIB.Topic({
            ros: ros,
            name: '/flash_detector/detection',
            messageType: 'std_msgs/Float32MultiArray'
        });

        detectionSub.subscribe((msg) => {
            if (msg.data && msg.data.length >= 5) {
                detectionData = {
                    cx: msg.data[0],
                    cy: msg.data[1],
                    area: msg.data[2],
                    sightX: msg.data[3],
                    sightY: msg.data[4]
                };

                if (onDetectionData) {
                    onDetectionData(detectionData);
                }
            }
        });
    }

    /**
     * 获取当前检测状态
     */
    function isFlashDetected() {
        return flashDetected;
    }

    /**
     * 获取当前检测数据
     */
    function getDetectionData() {
        return { ...detectionData };
    }

    /**
     * 计算相对位置 (相对于图像中心)
     * @returns {Object} {x: -1~1 (负值=左侧), y: -1~1 (负值=上方)}
     */
    function getRelativePosition() {
        if (imageWidth === 0 || imageHeight === 0) {
            return { x: 0, y: 0 };
        }

        const centerX = imageWidth / 2;
        const centerY = imageHeight / 2;

        return {
            x: (detectionData.cx - centerX) / centerX,  // -1 (左) ~ 1 (右)
            y: (detectionData.cy - centerY) / centerY    // -1 (上) ~ 1 (下)
        };
    }

    /**
     * 计算视线偏移角度 (弧度)
     * @returns {Object} {x: radians, y: radians}
     */
    function getSightAngles() {
        return {
            x: detectionData.sightX,
            y: detectionData.sightY
        };
    }

    /**
     * 设置图像尺寸 (用于计算相对位置)
     */
    function setImageSize(width, height) {
        imageWidth = width;
        imageHeight = height;
    }

    /**
     * 关闭模块
     */
    function shutdown() {
        if (flashDetectedSub) {
            flashDetectedSub.unsubscribe();
            flashDetectedSub = null;
        }
        if (detectionSub) {
            detectionSub.unsubscribe();
            detectionSub = null;
        }
        console.log('[Flash Detector] 模块已关闭');
    }

    return {
        init,
        isFlashDetected,
        getDetectionData,
        getRelativePosition,
        getSightAngles,
        setImageSize,
        shutdown
    };
})();
