#include "genthumbnail.h"
#include "../src/rawimage.h"
#include "../src/loadimage.h"

int generateThumbnail(const QString &input, const QString &output, uint32_t size)
{
    ImageInfoData info;
    std::shared_ptr<RawImage> rawImage;
    if(!loadImage(input, info, rawImage, 0))
        return 2;

    if(!rawImage)
        return 3;

    QSize rect(rawImage->width(), rawImage->height());
    rect.scale(size, size, Qt::KeepAspectRatio);
    rawImage->calcStats();
    rawImage->resize(rect.width(), rect.height());
    if(rawImage->imageStats().m_median[0] < rawImage->norm() * 0.2f)
    {
        MTFParam mtfParams = rawImage->calcMTFParams(true);
        rawImage->applySTF(mtfParams);
    }
    rawImage->convertToType(RawImage::UINT8);

    QImage img;
    if(rawImage->channels() == 1)
        img = QImage((const uchar*)rawImage->data(), rawImage->width(), rawImage->height(), rawImage->widthBytes(), QImage::Format_Grayscale8);
    else
        img = QImage((const uchar*)rawImage->data(), rawImage->width(), rawImage->height(), rawImage->widthBytes(), QImage::Format_RGBA8888);

    if(!img.save(output, "png"))
        return 4;

    return 0;
}
