/*
  SPDX-FileCopyrightText: 2016-2026 Laurent Montel <montel@kde.org>

  SPDX-License-Identifier: GPL-2.0-only
*/

#include "renamescriptjob.h"
#include "kmanagesieve/sievejob.h"

#include <KLocalizedString>
using namespace KSieveCore;

class KSieveCore::RenameScriptJobPrivate
{
public:
    QString mNewName;
    QUrl mOldUrl;
    QUrl mNewUrl;
    bool mIsActive = false;
};

RenameScriptJob::RenameScriptJob(QObject *parent)
    : QObject(parent)
    , d(new RenameScriptJobPrivate)
{
}

RenameScriptJob::~RenameScriptJob() = default;

void RenameScriptJob::setOldUrl(const QUrl &url)
{
    d->mOldUrl = url;
}

void RenameScriptJob::setIsActive(bool active)
{
    d->mIsActive = active;
}

void RenameScriptJob::setNewName(const QString &newName)
{
    d->mNewName = newName;
}

bool RenameScriptJob::canStart() const
{
    return !d->mNewName.trimmed().isEmpty() && d->mOldUrl.isValid();
}

void RenameScriptJob::start()
{
    if (canStart()) {
        KManageSieve::SieveJob *job = KManageSieve::SieveJob::get(d->mOldUrl);
        connect(job, &KManageSieve::SieveJob::result, this, &RenameScriptJob::slotGetResult);
    } else {
        Q_EMIT finished(d->mOldUrl, d->mNewUrl, i18n("Impossible to start job"), false);
        deleteLater();
    }
}

void RenameScriptJob::slotGetResult([[maybe_unused]] KManageSieve::SieveJob *job, bool success, const QString &script, [[maybe_unused]] bool isActive)
{
    if (!success) {
        Q_EMIT finished(d->mOldUrl, d->mNewUrl, i18n("An error occurred during loading the sieve script."), false);
        deleteLater();
        return;
    }
    QUrl u = d->mOldUrl;
    u = u.adjusted(QUrl::RemoveFilename);
    u.setPath(u.path() + d->mNewName);
    d->mNewUrl = u;
    KManageSieve::SieveJob *putJob = KManageSieve::SieveJob::put(d->mNewUrl, script, d->mIsActive, d->mIsActive);
    connect(putJob, &KManageSieve::SieveJob::result, this, &RenameScriptJob::slotPutScript);
}

void RenameScriptJob::slotPutScript([[maybe_unused]] KManageSieve::SieveJob *job, bool success)
{
    if (!success) {
        Q_EMIT finished(d->mOldUrl, d->mNewUrl, i18n("An error occurred during saving the sieve script."), false);
        deleteLater();
        return;
    }
    KManageSieve::SieveJob *deleteJob = KManageSieve::SieveJob::del(d->mOldUrl);
    connect(deleteJob, &KManageSieve::SieveJob::result, this, &RenameScriptJob::slotDeleteResult);
}

void RenameScriptJob::slotDeleteResult([[maybe_unused]] KManageSieve::SieveJob *job, bool success)
{
    Q_EMIT finished(d->mOldUrl, d->mNewUrl, success ? QString() : i18n("An error occurred during deleting the sieve script."), success);
    deleteLater();
}

#include "moc_renamescriptjob.cpp"
