#include "dbFunc.h"
#include "dbmana.h"
#include <QCoreApplication>
#include <QFileInfo>
#include <QProcess>
#include <QDateTime>
#include <QVariant>
#include <QDebug>

#define DEFAULT_SQLITE_MAX_LINE 1000000
#define SAVE_HISTORY_TIME 1 * 1000
#define RAWDATA_FILE_MAXSIZE (1UL*1024*1024)//2M

DBFunc::DBFunc(QObject *parent)
    : QObject(parent)
    , m_dbThread(nullptr)
    , m_stopFlag(false)
{
    qDebug() << "DBFunc: Database function module initialized";
}

DBFunc::~DBFunc()
{
    stopDBThread();
    qDebug() << "DBFunc: Database function module destroyed";
}

void DBFunc::startDBThread(const QString& sensorDataTableName)
{
    if (m_dbThread && m_dbThread->isRunning()) {
        qWarning() << "DBFunc: Database thread is already running";
        return;
    }

    m_stopFlag = false;
    m_currentTableName = sensorDataTableName;

    // 创建新线程
    m_dbThread = new QThread();

    // 将当前对象移动到新线程
    this->moveToThread(m_dbThread);

    // 连接线程启动信号到工作函数
    connect(m_dbThread, &QThread::started, this, [this, sensorDataTableName]() {
        this->DBThreadFun(sensorDataTableName);
    });

    // 连接线程结束信号
    connect(m_dbThread, &QThread::finished, this, [this]() {
        qDebug() << "DBFunc: Database thread finished";
        this->moveToThread(QThread::currentThread()); // 移回主线程
    });

    connect(m_dbThread, &QThread::finished, m_dbThread, &QObject::deleteLater);

    // 启动线程
    m_dbThread->start();
    qDebug() << "DBFunc: Database thread started for table:" << sensorDataTableName;
}

void DBFunc::stopDBThread()
{
    if (m_dbThread && m_dbThread->isRunning()) {
        qDebug() << "DBFunc: Stopping database thread...";
        m_stopFlag = true;

        // 发送退出信号到队列
        m_blockQueue_DB.enqueue(SIGER_EXIT);

        // 等待线程结束
        m_dbThread->quit();
        if (!m_dbThread->wait(3000)) { // 等待3秒
            qWarning() << "DBFunc: Thread not responding, terminating...";
            m_dbThread->terminate();
            m_dbThread->wait();
        }

        m_dbThread = nullptr;
        qDebug() << "DBFunc: Database thread stopped";
    }
}

void DBFunc::addDataToQueue(const std::string& data)
{
    if (!m_stopFlag && m_dbThread && m_dbThread->isRunning()) {
        m_blockQueue_DB.enqueue(data);
    } else {
        qWarning() << "DBFunc: Thread not running, cannot add data to queue";
    }
}

bool DBFunc::isRunning() const
{
    return m_dbThread && m_dbThread->isRunning() && !m_stopFlag;
}

void DBFunc::DBThreadFun(QString sensorDataTableName)
{
    // 原有的DBThreadFun实现代码保持不变
    // ... [你原有的DBThreadFun代码]

    QString dbPath = QString("/home/pi/SigerTMS/stream/SAC/%1.db").arg(sensorDataTableName);

    qDebug()<<" GLS file Path:"<<dbPath;

    QString createTable = QString(
        "CREATE TABLE IF NOT EXISTS %1("
        "id INTEGER PRIMARY KEY AUTOINCREMENT, "
        "StartTime TEXT NOT NULL, "
        "EndTime TEXT NOT NULL, "
        "target TEXT NOT NULL, "
        "Label INTEGER NOT NULL, "
        "x TEXT NOT NULL, "
        "y TEXT NOT NULL, "
        "z TEXT NOT NULL, "
        "created_at TEXT DEFAULT CURRENT_TIMESTAMP)"
    ).arg(sensorDataTableName);

    DBMana::execute(createTable, "sensorDataTableName", dbPath);

    QString CountTable = QString("SELECT COUNT(rowid) FROM %1").arg(sensorDataTableName);
    QSqlQuery* querycount = DBMana::select(CountTable, "sensorDataTableName", dbPath);

    if (querycount->next()) {
        m_sensor_dataCountDB = querycount->value(0).toInt();
    }
    querycount->clear();

    QString compressPath = "";

    while(!m_stopFlag) {
        std::string tmp = "";

        // 压缩db文件逻辑
        if(m_sensor_dataCountDB >= DEFAULT_SQLITE_MAX_LINE) {
            // ... [你原有的压缩逻辑]
        }

        // db文件压缩时，会将文件重命名
        if (!QFile::exists(dbPath)) {
            DBMana::destroyConn("sensorDataTableName", dbPath);
            DBMana::execute(createTable, "sensorDataTableName", dbPath);
        }

        m_blockQueue_DB.wait_dequeue(tmp);

        if(tmp!="")
        {
            qDebug()<<"GLS sql"<<tmp.c_str();
        }

        if(tmp == SIGER_EXIT) {
            qDebug() << "DBFunc: Received exit signal";
            break;
        }

        if(DBMana::execute(QString::fromStdString(tmp), "sensorDataTableName", dbPath)) {
            qDebug()<<tmp.c_str();
            m_sensor_dataCountDB = m_sensor_dataCountDB + 1;
        }

        // 定期处理事件，保持响应性
        QCoreApplication::processEvents();
    }

    qDebug() << "DBFunc: Database thread function exited";
}
