#include "mqttthread.h"

#include "./mqtt/mqttclient.h"  // 假设 MqttClient 类的头文件是 mqttclient.h
#include "logger.h"

MqttThread::MqttThread(QObject *parent) : QThread(parent) {}

MqttThread::~MqttThread() {
    m_stopFlag = true;
    quit();
    wait();
    if (mqttClient) {
        delete mqttClient;
    }
}

void MqttThread::setConnectionInfo(const QString &hostname, quint16 port, const QString &username,
                                   const QString &password, const QString &clientId,
                                   const QStringList &topicsToSubscribe) {
    m_hostname = hostname;
    m_port = port;
    m_username = username;
    m_password = password;
    m_clientId = clientId;
    m_topicsToSubscribe = topicsToSubscribe;
}

MqttClient *MqttThread::getMqttClient() const { return mqttClient; }

void MqttThread::stopThread() {
    m_stopFlag = true;
    quit();
}

void MqttThread::run() {
    // mqttClient = new MqttClient();
    mqttClient = MqttClient::createNewInstance();
    mqttClient->connectToMqttBroker(m_hostname, m_port, m_username, m_password, m_clientId,
                                    m_topicsToSubscribe);

    connect(mqttClient, &MqttClient::connected, this, &MqttThread::mqttConnected);
    connect(mqttClient, &MqttClient::messageAndTopicReceived, this,
            &MqttThread::projectMqttMessageReceived);
    connect(this, &MqttThread::sendMessageRequested, mqttClient, &MqttClient::sendMessage);
    while (!m_stopFlag) {
        exec();
    }
}

void MqttThread::sendMqttMessage(const QString &topic, const QByteArray &message, quint8 qos,
                                 bool isRetainedMsg) {
    if (mqttClient) {
        Logger::getInstance().info(
            QString("Mqtt thread 发送MQTT消息到主题: %1, 消息: %2, qos: %3, isRetainMsg: %4")
                .arg(topic, QString(message), qos, isRetainedMsg ? "true" : "false"));
        mqttClient->sendMessage(topic, message, qos, isRetainedMsg);
    }
}
