// storageworker.cpp
#include "storageworker.h"
#include <QDateTime>
#include <QDir>
#include <QDebug>
#include <QStandardPaths>

StorageWorker::StorageWorker(QObject *parent)
    : QObject(parent)
{
}

StorageWorker::~StorageWorker()
{
}

QString StorageWorker::getSaveDirectory()
{
    QString baseDir = QStandardPaths::writableLocation(QStandardPaths::DesktopLocation);
    return baseDir;
}

void StorageWorker::process()
{
    while (true)
    {
        ImageData data;

        if (!g_storageQueue.dequeue(data))
        {
            // 队列已停止且为空，退出循环
            break;
        }

        if (data.image.empty())
        {
            qWarning() << "Received empty image for camera" << data.camera_id;
            continue;
        }

        // 定义保存路径，例如使用时间戳
        QString saveDir = (getSaveDirectory() + QString("/Cam_%1/")).arg(data.camera_id == 0 ? "1" : "2");
        QDir dir;
        if (!dir.exists(saveDir))
        {
            dir.mkpath(saveDir);
        }

        QString timestamp = QDateTime::currentDateTime().toString("yyyyMMdd_HHmmss_zzz");
        QString filePath = saveDir + QString("%1.bmp").arg(timestamp);

        // 使用 OpenCV 直接保存图像
        if (cv::imwrite(filePath.toStdString(), data.image))
        {
            qDebug() << "Successfully saved image to" << filePath;
        }
        else
        {
            qWarning() << "Failed to save image to" << filePath;
        }
    }
}
