#pragma once

#include <rclcpp/rclcpp.hpp>
#include <atomic>
#include <netinet/in.h>
#include <string>
#include <thread>

#include "protocol.h"

/**
 * @brief 设备信息发送节点
 *
 * 通过 UDP 端口 10000 定期广播设备信息，并响应请求包（DEVICE_INFO_REQUEST）。
 */
class DeviceInfoSenderNode : public rclcpp::Node {
public:
    DeviceInfoSenderNode();
    ~DeviceInfoSenderNode();

private:
    void load_parameters();
    void start_listener();
    void stop_listener();

    void broadcast_timer_callback();
    void handle_request_loop();
    void send_device_info(const sockaddr_in& addr);
    DeviceInfoPacket build_packet();
    static uint64_t htonll(uint64_t value);
    static uint32_t fourcc_from_string(const std::string& fmt);

private:
    // 套接字
    int udp_socket_{-1};
    std::atomic<bool> running_{false};
    std::thread listener_thread_;

    // 参数
    uint16_t info_port_{10000};
    std::string target_ip_{"255.255.255.255"};
    bool enable_broadcast_{true};
    bool enable_request_response_{true};
    int broadcast_interval_ms_{1000};

    // 设备信息
    std::string device_path_{"/dev/video0"};
    std::string device_name_{"Unknown"};
    uint16_t width_{0};
    uint16_t height_{0};
    float framerate_{0.0f};
    uint32_t pixel_format_{0};
    float current_fps_{0.0f};
    uint32_t total_frames_{0};
    uint32_t sequence_{0};

    rclcpp::TimerBase::SharedPtr broadcast_timer_;
};
