#pragma once

#include <string>
#include <mqtt/async_client.h>
#include <chrono>
#include <mutex>

class MqttClient
{
public:
    MqttClient(const std::string &configPath);
    ~MqttClient();

    bool start();      // 连接并订阅
    void disconnect(); // 断开连接

    // 让外部可以访问最新的 gear 和 speed
    int getGear();
    double getSpeed();
    void checkTimeout(std::chrono::seconds timeout);

private:
    std::string broker;
    std::string clientId;
    std::string username;
    std::string password;
    std::string topic;
    int qos;

    // 让回调持有指向MqttClient的指针，方便修改成员变量
    class Callback : public virtual mqtt::callback
    {
    public:
        explicit Callback(MqttClient *parent) : parent(parent) {}
        void message_arrived(mqtt::const_message_ptr msg) override;

    private:
        MqttClient *parent;
    };

    mqtt::async_client *client = nullptr;
    mqtt::connect_options connOpts;
    Callback callback{this}; // 初始化时传入 this 指针

    // 存储解析结果
    int gear = 0;
    double speed = 0.0;
    std::chrono::steady_clock::time_point lastMessageTime = std::chrono::steady_clock::now();
    std::mutex dataMutex;
};
