// SPDX-FileCopyrightText: 2019 - 2023 UnionTech Software Technology Co., Ltd.
//
// SPDX-License-Identifier: GPL-3.0-or-later

#include "imageprocess.h"
#include <QBuffer>
#include <QMimeData>
#include <QString>
#include <QByteArray>
#include "clipboarddataprocess.h"

ImageDataProcess::ImageDataProcess()
{
}
// 将QImage转换为QVariant
QVariant ImageDataProcess::toVariant(const QImage &pixmap)
{
    QByteArray ba;
    QBuffer buffer(&ba);
    buffer.open(QIODevice::WriteOnly);
    pixmap.save(&buffer, "PNG"); // 选择一个支持的图片格式
    buffer.close();
    return QVariant(ba);
}

// 将QVariant转换回QImage
QImage ImageDataProcess::toImage(const QVariant &variant)
{
    QImage pixmap;
    if (variant.type() == QVariant::ByteArray) {
        QByteArray ba = variant.toByteArray();
        QBuffer buffer(&ba);
        buffer.open(QIODevice::ReadOnly);
        pixmap.load(&buffer, "PNG"); // 使用与存储时相同的格式
        buffer.close();
    }
    return pixmap;
}

vector<char> ImageDataProcess::scaleImage(const vector<char> &vData, const string type, int &w, int &h, int &rw, int &rh)
{
    vector<char> vSmalldata;
    QByteArray ba = QByteArray::fromRawData(vData.data(), vData.size());

    QImage srcPix;
    srcPix.loadFromData(ba);
    if (!srcPix.isNull()) {
        rw = srcPix.width();
        rh = srcPix.height();

        QImage img = srcPix.width() * PixmapHeight > srcPix.height() * PixmapWidth ? srcPix.scaledToWidth(PixmapWidth, Qt::SmoothTransformation) : srcPix.scaledToHeight(PixmapHeight, Qt::SmoothTransformation);

        w = img.width();
        h = img.height();
        QVariant variant = toVariant(img);
        QByteArray vBa = variant.toByteArray();
        vSmalldata = std::vector<char>(vBa.cbegin(), vBa.cend());
    }

    return vSmalldata;
}

QImage ImageDataProcess::toImage(const vector<char> &vData, const string type)
{
    QByteArray ba = QByteArray::fromRawData(vData.data(), vData.size());
    QMimeData mimeData;
    mimeData.setData(QString::fromStdString(type), ba);

    QImage img;
    if (mimeData.hasImage()) {
        img = qvariant_cast<QImage>(mimeData.imageData());
    }
    return img;
}
