/*
 * SPDX-FileCopyrightText: 2010 Thomas McGuire <mcguire@kde.org>
 *
 * SPDX-License-Identifier: LGPL-2.1-or-later
 */
#include "inserttextfilejob.h"

#include <QTextEdit>

#include "editor_debug.h"

#include <QNetworkAccessManager>
#include <QNetworkReply>
#include <QPointer>
#include <QStringDecoder>

using namespace MessageComposer;
class MessageComposer::InsertTextFileJobPrivate
{
public:
    InsertTextFileJobPrivate(QTextEdit *editor, const QUrl &url)
        : mEditor(editor)
        , mUrl(url)
    {
    }

    QPointer<QTextEdit> mEditor;
    QUrl mUrl;
    QString mEncoding;
    QByteArray mFileData;
};

InsertTextFileJob::InsertTextFileJob(QTextEdit *editor, const QUrl &url)
    : KJob(editor)
    , d(new MessageComposer::InsertTextFileJobPrivate(editor, url))
{
}

InsertTextFileJob::~InsertTextFileJob() = default;

void InsertTextFileJob::slotGetJobFinished(QNetworkReply *reply)
{
    if (reply->error() != QNetworkReply::NoError) {
        qCWarning(EDITOR_LOG) << reply->errorString();
        setError(reply->error());
        setErrorText(reply->errorString());
        emitResult();
        return;
    }

    if (d->mEditor) {
        if (!d->mEncoding.isEmpty()) {
            QStringDecoder fileCodec(d->mEncoding.toLatin1().constData());
            if (fileCodec.isValid()) {
                d->mEditor->textCursor().insertText(fileCodec.decode(d->mFileData.data()));
            } else {
                d->mEditor->textCursor().insertText(QString::fromLocal8Bit(d->mFileData.data()));
            }
        } else {
            d->mEditor->textCursor().insertText(QString::fromLocal8Bit(d->mFileData.data()));
        }
    }

    emitResult();
}

void InsertTextFileJob::setEncoding(const QString &encoding)
{
    d->mEncoding = encoding;
}

void InsertTextFileJob::start()
{
    auto qnam = new QNetworkAccessManager(this);
    QNetworkRequest request(d->mUrl);
    auto reply = qnam->get(request);
    connect(reply, &QNetworkReply::finished, this, [this, reply]() {
        slotGetJobFinished(reply);
    });
}

#include "moc_inserttextfilejob.cpp"
