#pragma once

#include "paho_mqtt_3c/MQTTClient.h"
#include <string>
#include <iostream>

class MQTTClientWrapper
{
public:
    MQTTClientWrapper(const std::string &server_address, const std::string &client_id,
                      const std::string &username = "", const std::string &password = "")
        : server_address_(server_address), client_id_(client_id), 
          username_(username), password_(password), client_(nullptr)
    {
        // 初始化客户端
        int rc = MQTTClient_create(&client_, server_address.c_str(), client_id.c_str(),
                                 MQTTCLIENT_PERSISTENCE_NONE, nullptr);
        if (rc != MQTTCLIENT_SUCCESS)
        {
            std::cerr << "Failed to create MQTT client, return code " << rc << std::endl;
            client_ = nullptr;
        }
    }

    ~MQTTClientWrapper()
    {
        if (client_)
        {
            disconnect();
            MQTTClient_destroy(&client_);
            client_ = nullptr;
        }
    }

    bool connect()
    {
        if (!client_)
        {
            std::cerr << "MQTT client not initialized" << std::endl;
            return false;
        }

        MQTTClient_connectOptions conn_opts = MQTTClient_connectOptions_initializer;
        conn_opts.keepAliveInterval = 20;
        conn_opts.cleansession = 1;
        
        if (!username_.empty())
        {
            conn_opts.username = username_.c_str();
            conn_opts.password = password_.c_str();
        }

        int rc = MQTTClient_connect(client_, &conn_opts);
        if (rc != MQTTCLIENT_SUCCESS)
        {
            std::cerr << "Failed to connect, return code " << rc << std::endl;
            return false;
        }

        std::cout << "MQTT connected successfully" << std::endl;
        return true;
    }

    void disconnect()
    {
        if (client_)
        {
            int rc = MQTTClient_disconnect(client_, 10000);
            if (rc != MQTTCLIENT_SUCCESS)
            {
                std::cerr << "Failed to disconnect, return code " << rc << std::endl;
            }
            else
            {
                std::cout << "MQTT disconnected." << std::endl;
            }
        }
    }

    void publish(const std::string &topic, const std::string &payload, int qos = 1, bool retained = false)
    {
        if (!client_)
        {
            std::cerr << "MQTT client not initialized" << std::endl;
            return;
        }

        MQTTClient_message pubmsg = MQTTClient_message_initializer;
        MQTTClient_deliveryToken token;

        pubmsg.payload = const_cast<char*>(payload.c_str());
        pubmsg.payloadlen = payload.length();
        pubmsg.qos = qos;
        pubmsg.retained = retained ? 1 : 0;

        int rc = MQTTClient_publishMessage(client_, topic.c_str(), &pubmsg, &token);
        if (rc != MQTTCLIENT_SUCCESS)
        {
            std::cerr << "Failed to publish message, return code " << rc << std::endl;
            return;
        }

        // 等待发布完成
        rc = MQTTClient_waitForCompletion(client_, token, 10000L);
        if (rc != MQTTCLIENT_SUCCESS)
        {
            std::cerr << "Failed to wait for completion, return code " << rc << std::endl;
        }
        else
        {
            // 可选：取消注释以打印发布信息
            // std::cout << "Published to " << topic << std::endl;
        }
    }

private:
    std::string server_address_;
    std::string client_id_;
    std::string username_;
    std::string password_;
    MQTTClient client_;
};
