/*
  SPDX-FileCopyrightText: 2009 Constantin Berzan <exit3219@gmail.com>

  Parts based on KMail code by various authors.

  SPDX-License-Identifier: LGPL-2.0-or-later
*/

#include "attachmentfromurljob.h"

#include "editor_debug.h"
#include <KFormat>
#include <KLocalizedString>

#include <QFileInfo>
#include <QMimeDatabase>
#include <QNetworkAccessManager>
#include <QNetworkReply>
#include <QUrlQuery>

using namespace MessageCore;

class MessageCore::AttachmentFromUrlJob::AttachmentLoadJobPrivate
{
public:
    explicit AttachmentLoadJobPrivate(AttachmentFromUrlJob *qq);

    void slotRequestFinished(QNetworkReply *reply);

    AttachmentFromUrlJob *const q;
    QByteArray mData;
};

AttachmentFromUrlJob::AttachmentLoadJobPrivate::AttachmentLoadJobPrivate(AttachmentFromUrlJob *qq)
    : q(qq)
{
}

void AttachmentFromUrlJob::AttachmentLoadJobPrivate::slotRequestFinished(QNetworkReply *reply)
{
    if (reply->error() != QNetworkReply::NoError) {
        // TODO this loses useful stuff from KIO, like detailed error descriptions, causes+solutions,
        // ... use UiDelegate somehow?
        q->setError(reply->error());
        q->setErrorText(reply->errorString());
        q->emitResult();
        return;
    }

    mData = reply->readAll();

    // Determine the MIME type and filename of the attachment.
    const QString mimeTypeName = reply->header(QNetworkRequest::ContentTypeHeader).toString();
    qCDebug(EDITOR_LOG) << "Mimetype is" << mimeTypeName;

    QString fileName = q->url().fileName();
    fileName.replace(QLatin1Char('\n'), QLatin1Char('_'));
    if (fileName.isEmpty()) {
        QMimeDatabase db;
        const auto mimeType = db.mimeTypeForName(mimeTypeName);
        if (mimeType.isValid()) {
            fileName = i18nc("a file called 'unknown.ext'", "unknown%1", mimeType.preferredSuffix());
        } else {
            fileName = i18nc("a file called 'unknown'", "unknown");
        }
    }

    // Create the AttachmentPart.
    Q_ASSERT(q->attachmentPart() == nullptr); // Not created before.

    AttachmentPart::Ptr part = AttachmentPart::Ptr(new AttachmentPart);
    part->setMimeType(mimeTypeName.toLatin1());
    part->setName(fileName);
    part->setFileName(fileName);
    part->setData(mData);
    part->setUrl(q->url());
    q->setAttachmentPart(part);
    q->emitResult(); // Success.
}

AttachmentFromUrlJob::AttachmentFromUrlJob(const QUrl &url, QObject *parent)
    : AttachmentFromUrlBaseJob(url, parent)
    , d(new AttachmentLoadJobPrivate(this))
{
}

AttachmentFromUrlJob::~AttachmentFromUrlJob() = default;

void AttachmentFromUrlJob::doStart()
{
    if (!url().isValid()) {
        setError(KJob::UserDefinedError);
        setErrorText(i18n("\"%1\" not found. Please specify the full path.", url().toDisplayString()));
        emitResult();
        return;
    }

    if (maximumAllowedSize() != -1 && url().isLocalFile()) {
        const qint64 size = QFileInfo(url().toLocalFile()).size();
        if (size > maximumAllowedSize()) {
            setError(KJob::UserDefinedError);
            KFormat format;
            setErrorText(i18n("You may not attach files bigger than %1. Share it with storage service.", format.formatByteSize(maximumAllowedSize())));
            emitResult();
            return;
        }
    }

    Q_ASSERT(d->mData.isEmpty()); // Not started twice.
    if (url().scheme() == QLatin1StringView("https") || url().scheme() == QLatin1StringView("http")) {
        auto qnam = new QNetworkAccessManager(this);
        QNetworkRequest request(url());
        auto reply = qnam->get(request);
        connect(reply, &QNetworkReply::finished, this, [this, reply]() {
            d->slotRequestFinished(reply);
        });
    } else if (url().scheme() == QLatin1StringView("file")) {
        QFile file(url().toLocalFile());
        if (!file.open(QIODeviceBase::ReadOnly)) {
            setError(KJob::UserDefinedError);
            setErrorText(i18n("Could not read file \"%1\".", url().toDisplayString()));
            emitResult();
            return;
        }
        QString fileName = url().fileName();
        QMimeDatabase db;
        const auto mimeType = db.mimeTypeForFile(url().toLocalFile());
        if (mimeType.isValid()) {
            fileName = i18nc("a file called 'unknown.ext'", "unknown%1", mimeType.preferredSuffix());
        } else {
            fileName = i18nc("a file called 'unknown'", "unknown");
        }

        // Create the AttachmentPart.
        Q_ASSERT(attachmentPart() == nullptr); // Not created before.

        AttachmentPart::Ptr part = AttachmentPart::Ptr(new AttachmentPart);
        part->setMimeType(mimeType.name().toUtf8());
        part->setName(fileName);
        part->setFileName(fileName);
        part->setData(file.readAll());
        part->setUrl(url());
        setAttachmentPart(part);
        emitResult(); // Success.
        return;
    }

    setError(KJob::UserDefinedError);
    setErrorText(i18n("scheme not supported \"%1\".", url().scheme()));
    emitResult();
}

#include "moc_attachmentfromurljob.cpp"
