/**
    Read Common Image Formats

    Generate metadata, preview, and thumbnails for EkosLive Offline Viewer.

    2020 Jasem Mutlaq
    Ikarus Technologies
**/

#include "common_formats.h"

#include <QJsonDocument>
#include <QJsonObject>
#include <QFileInfo>
#include <QDateTime>
#include <QUuid>
#include <QRegularExpression>

namespace CommonFormats
{

QByteArray metadata(const QString &filename)
{
    QJsonObject meta;

    QImage image(filename);
    if (image.isNull())
        return QByteArray();

    QFileInfo info = QFileInfo(filename);

    meta.insert("naxis1", image.width());
    meta.insert("naxis2", image.height());

    meta.insert("exptime", 1);
    meta.insert("naxis", 2);
    meta.insert("bitpix", 16);
    meta.insert("bscale", 1);
    meta.insert("bzero", 32768);

#if QT_VERSION >= QT_VERSION_CHECK(5,10,0)
    QDateTime fileTS = info.birthTime();
    if (!fileTS.isValid())
    {
        fileTS = info.metadataChangeTime();
        if (!fileTS.isValid())
            fileTS = QDateTime::currentDateTime();
    }
#else
    QDateTime fileTS = info.created();
    if (!fileTS.isValid())
        fileTS = QDateTime::currentDateTime();
#endif
    meta.insert("date-obs", fileTS.toString(Qt::ISODate));
    meta.insert("xbinning", 1);
    meta.insert("ybinning", 1);

    QString frame = "Light";
    if (filename.contains("Dark/"))
        frame = "Dark";
    else if (filename.contains("Flat/"))
        frame = "Flat";
    else if (filename.contains("Bias/"))
        frame = "Bias";

    meta.insert("frame", frame);

    QString filenameOnly = QFileInfo(filename).fileName();
    int32_t size = QFileInfo(filename).size();
    QString m_UUID = QUuid::createUuid().toString();
    m_UUID = m_UUID.remove(QRegularExpression("[-{}]"));

    // Add filename and size as wells
    meta.insert("uuid", m_UUID);
    meta.insert("filename", filenameOnly);
    meta.insert("filesize", size);
    meta.insert("Content-Disposition", QString("attachment;filename=%1").arg(filenameOnly));


    return QJsonDocument(meta).toJson(QJsonDocument::Compact);
}

QImage toImage(const QString &filename, int maxWidth, int quality)
{
    QImage image(filename);

    // Resize if necessary
    if (maxWidth > 0 && image.width() > maxWidth)
        image = image.scaledToWidth(maxWidth, quality > 50 ? Qt::SmoothTransformation : Qt::FastTransformation);

    return image;
}

}
