#include "loadimage.h"
#include <QDebug>
#include <QPixmap>
#include <QThread>
#include <CImg.h>
LoadImage::LoadImage(QObject *parent) : QObject(parent)
{
    m_flag = false;
}
void LoadImage::setFlag(bool res){
    m_flag = res;
}
void LoadImage::loadImageToWidget(QString loadPath, QString save_path, QImage *img, QLabel *container, double scale, bool rotationFlag, QSize labSize){
    if(m_flag){
        m_flag = false;
        return;
    }
    QFileInfo loadPathInfo(loadPath);
    QString newLoadPath = loadPathInfo.absolutePath() + "/" + loadPathInfo.baseName() + ".jpg";

    loadAndSave(newLoadPath, loadPath);

    //    cv::imwrite(std::string(newLoadPath.toLocal8Bit().data()), KylinImageCodec::loadImageToMat(loadPath).mat);

    img->load(newLoadPath);


    double proportion;
    {
        if (img->isNull()) {
            qDebug() << "image is null.";
            return;
        }
        double labWidth = labSize.width();
        double labHeight = labSize.height();

        double imgWidth = img->width();
        double imgHeight = img->height();

        if(rotationFlag){
            double tmp = imgWidth;
            imgWidth = imgHeight;
            imgHeight = tmp;
        }


        if (! qFuzzyCompare(scale, 1.0)) {
            proportion = scale;
        } else {
            if ((labWidth / imgWidth) <= (labHeight / imgHeight)) {
                proportion = labWidth / imgWidth;
            } else {
                proportion = labHeight / imgHeight;
            }
        }

        QPixmap pixmap = QPixmap::fromImage(*img);

        QPixmap fitpixmap =pixmap.scaled(img->size()*proportion, Qt::KeepAspectRatio, Qt::SmoothTransformation);
        container->setPixmap(fitpixmap);
        container->setFixedSize(QSize(fitpixmap.size()));
        container->setScaledContents(true);
        container->setAlignment(Qt::AlignCenter | Qt::AlignVCenter | Qt::AlignHCenter);
    }
    QImage image = *img;
    qDebug() << &image << " " << img;
    if(m_flag){
        m_flag = false;
        return;
    }
    emit finished(save_path, proportion, image);
}

void LoadImage::loadAndSave(QString newLoadPath, QString loadPath)
{
    cimg_library::CImg<unsigned char> img(loadPath.toLocal8Bit().data());
    if(!QFile(newLoadPath).exists()){
        img.save_jpeg(newLoadPath.toLocal8Bit().data());
    }
}

