/*
 * Copyright (C) 2020, KylinSoft Co., Ltd.
 *
 * This program 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 3 of the License, or
 * (at your option) any later version.
 *
 * This program 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 this program.  If not, see <https://www.gnu.org/licenses/>.
 */
#include "albumthumbnail.h"

AlbumThumbnail::AlbumThumbnail(const QString &path, const QString &realFormat)
{
    m_path = path;
    m_realFormat = realFormat;
}

void AlbumThumbnail::run()
{
    ImageAndInfo thumbnail;
    QVariant varThumbnail, varImageCache;
    QPair<MatAndFileinfo, QPixmap> matPix;
    MatAndFileinfo maf = File::loadImage(m_path, m_realFormat);
    matPix.first = maf;
    if (maf.mat.data) {
        QPixmap pix = Processing::converFormat(maf.mat);
        matPix.second = pix;
        pix = pix.scaled(Variable::ALBUM_IMAGE_SIZE, Qt::KeepAspectRatio);  // 采用快速缩放
        thumbnail.image = changImageSize(pix);
    }
    thumbnail.info = maf.info;

    varThumbnail.setValue<ImageAndInfo>(thumbnail);
    varImageCache.setValue<QPair<MatAndFileinfo, QPixmap>>(matPix);
    Q_EMIT albumFinish(varThumbnail, varImageCache);
}

QPixmap AlbumThumbnail::changImageSize(const QPixmap &pix)
{
    if (pix.size() == QSize(Variable::ALBUM_IMAGE_SIZE.width(), Variable::ALBUM_IMAGE_SIZE.height() - 2)) {
        return pix;
    }

    int w = 0;
    int h = 0;

    w = Variable::ALBUM_IMAGE_SIZE.width() - pix.width();
    h = Variable::ALBUM_IMAGE_SIZE.height() - pix.height();

    QPixmap newPix(QSize(Variable::ALBUM_IMAGE_SIZE.width(), Variable::ALBUM_IMAGE_SIZE.height() - 2));
    newPix.fill(Qt::transparent);
    QPainter painter(&newPix);
    painter.drawPixmap(w / 2, h / 2, pix);
    return newPix;
}
