/*
 *   SPDX-FileCopyrightText: 2019 Guo Yunhe <i@guoyunhe.me>
 *
 *   SPDX-License-Identifier: GPL-2.0-or-later
 */

#include "unsplashprovider.h"

#include <QDebug>
#include <QRegularExpression>

#include <KIO/Job>
#include <KPluginFactory>

UnsplashProvider::UnsplashProvider(QObject *parent, const QVariantList &args)
    : PotdProvider(parent, args)
{
    QString collectionId = QStringLiteral("1065976");
    QRegularExpression re(QStringLiteral("^\\d+$"));
    for (int i = 1; i < args.count(); i++) {
        QString str = args[i].toString();
        if (re.match(str).hasMatch()) {
            collectionId = str;
        }
    }
    const QUrl url(QStringLiteral("https://source.unsplash.com/collection/%1/3840x2160/daily").arg(collectionId));

    KIO::StoredTransferJob *job = KIO::storedGet(url, KIO::NoReload, KIO::HideProgressInfo);
    connect(job, &KIO::StoredTransferJob::finished, this, &UnsplashProvider::imageRequestFinished);
}

UnsplashProvider::~UnsplashProvider() = default;

QImage UnsplashProvider::image() const
{
    return mImage;
}

void UnsplashProvider::imageRequestFinished(KJob *_job)
{
    KIO::StoredTransferJob *job = static_cast<KIO::StoredTransferJob *>(_job);
    if (job->error()) {
        Q_EMIT error(this);
        return;
    }
    QByteArray data = job->data();
    mImage = QImage::fromData(data);
    Q_EMIT finished(this);
}

K_PLUGIN_CLASS_WITH_JSON(UnsplashProvider, "unsplashprovider.json")

#include "unsplashprovider.moc"
