/**************************************************************************
 **                                                                      **
 ** Copyright (C) 2011-2026 Lukas Spies                                  **
 ** Contact: https://photoqt.org                                         **
 **                                                                      **
 ** This file is part of PhotoQt.                                        **
 **                                                                      **
 ** PhotoQt is free software: you can redistribute it and/or modify      **
 ** it under the terms of the GNU General Public License as published by **
 ** the Free Software Foundation, either version 2 of the License, or    **
 ** (at your option) any later version.                                  **
 **                                                                      **
 ** PhotoQt is distributed in the hope that it will be useful,           **
 ** but WITHOUT ANY WARRANTY; without even the implied warranty of       **
 ** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the        **
 ** GNU General Public License for more details.                         **
 **                                                                      **
 ** You should have received a copy of the GNU General Public License    **
 ** along with PhotoQt. If not, see <http://www.gnu.org/licenses/>.      **
 **                                                                      **
 **************************************************************************/

#include <pqc_loadimage_libvips.h>
#include <pqc_imagecache.h>
#include <scripts/pqc_scriptsimages.h>
#include <scripts/pqc_scriptscolorprofiles.h>
#include <pqc_notify_cpp.h>
#include <pqc_settingscpp.h>
#include <QSize>
#include <QtDebug>
#include <QImage>

#ifdef PQMLIBVIPS
#include <vips/vips.h>
#endif

PQCLoadImageLibVips::PQCLoadImageLibVips() {}

QSize PQCLoadImageLibVips::loadSize(QString filename) {

#ifdef PQMLIBVIPS

    // we only need the metadata here, never the full image
    VipsImage *in = vips_image_new_from_file(filename.toStdString().c_str(),
                                             "access", VIPS_ACCESS_RANDOM,
                                             "fail_on", VIPS_FAIL_ON_TRUNCATED,
                                             NULL);

    if(!in) {
        qDebug() << "vips_image_new_from_file: failed to load image from file)";
        return QSize();
        return QSize();
    }

    const QSize size(vips_image_get_width(in), vips_image_get_height(in));

    g_object_unref(in);

    return size;

#else

    return QSize();

#endif

}

QString PQCLoadImageLibVips::load(QString filename, QSize maxSize, QSize &origSize, QImage &img) {

    qDebug() << "args: filename = " << filename;
    qDebug() << "args: maxSize = " << maxSize;

    QString errormsg = "";

#ifdef PQMLIBVIPS

    // we use the C API as the equivalent C++ API calls led to crash on subsequent call

    // attempt to the load the image
    VipsImage *vimg = vips_image_new_from_file(filename.toStdString().c_str(), "access", VIPS_ACCESS_SEQUENTIAL, NULL);
    if(!vimg) {
        errormsg = "vips_image_new_from_file: failed to load image from file";
        qDebug() << errormsg;
        return errormsg;
    }

    // store original size
    origSize = QSize(vimg->Xsize, vimg->Ysize);

    // ensure a Qt-friendly format
    if(vips_image_hasalpha(vimg) == 0) {
        VipsImage *tmp;
        if(vips_addalpha(vimg, &tmp, NULL)) {
            errormsg = "vips_image_hasalpha failed";
            qDebug() << errormsg;
            return errormsg;
        }
        g_object_unref(vimg);
        vimg = tmp;
    }

    // convert to uchar RGBA
    VipsImage *memImg = vips_image_copy_memory(vimg);
    if(!memImg) {
        g_object_unref(vimg);
        errormsg = "vips_image_copy_memory failed";
        qDebug() << errormsg;
        return errormsg;
    }

    // construct qimage with clean-up function
    img = QImage(memImg->data,
                 origSize.width(), origSize.height(), origSize.width()*memImg->Bands,
                 QImage::Format_RGBA8888,
                 [](void *p) { g_object_unref(VIPS_IMAGE(p)); },
                 memImg);

    // apply transformations if any
    const QString suf = QFileInfo(filename).suffix().toLower();
    if(PQCSettingsCPP::get().getMetadataAutoRotation() && suf != "heif" && suf != "heic") {
        PQCScriptsImages::get().applyExifOrientation(filename, img);
    }

    // apply color profile if any
    PQCScriptsColorProfiles::get().applyColorProfile(filename, img);

    // cache the image
    PQCImageCache::get().saveImageToCache(filename, PQCScriptsColorProfiles::get().getColorProfileFor(filename), &img);

    // clean up memory
    g_object_unref(vimg);

    // scale image if necessary
    if(!maxSize.isEmpty()) {
        img = img.scaled(origSize.scaled(maxSize, Qt::KeepAspectRatio),
                         Qt::IgnoreAspectRatio,
                         (PQCSettingsCPP::get().getImageviewRescalingSmooth() ? Qt::SmoothTransformation : Qt::FastTransformation));
    }

    return "";

#endif
    origSize = QSize(-1,-1);
    errormsg = "Failed to load image, libvips not supported by this build of PhotoQt!";
    qDebug() << errormsg;
    return errormsg;

}
