// SPDX-FileCopyrightText: 2024 g10 Code GmbH
// SPDX-FileContributor: Carl Schwan <carl@carlschwan.eu>
//
// SPDX-License-Identifier: LGPL-2.1-or-later

#include "filereencryptjob.h"
#include "filedecryptjob.h"
#include "fileencryptjob.h"

#include <KLocalizedString>

FileReencryptJob::FileReencryptJob(const QString &filePath, const QList<QByteArray> recipients, QObject *parent)
    : KCompositeJob(parent)
    , m_filePath(filePath)
    , m_recipients(recipients)
{
}

void FileReencryptJob::start()
{
    auto decryptJob = new FileDecryptJob(m_filePath);
    connect(decryptJob, &KJob::result, this, [decryptJob, this](KJob *) {
        if (decryptJob->error() != KJob::NoError) {
            setError(decryptJob->error());
            setErrorText(xi18nc("@info", "Could not decrypt <filename>%1</filename>. %2", m_filePath, decryptJob->errorText()));
            emitResult();
            return;
        }

        const auto content = decryptJob->content().toUtf8();
        auto encryptJob = new FileEncryptJob(m_filePath, content, m_recipients);
        addSubjob(encryptJob);
        encryptJob->start();
        connect(encryptJob, &KJob::result, this, [encryptJob, this](KJob *) {
            if (encryptJob->error() != KJob::NoError) {
                setError(encryptJob->error());
                setErrorText(xi18nc("@info", "Could not re-encrypt <filename>%1</filename>. %2", m_filePath, encryptJob->errorText()));
                emitResult();
                return;
            }

            emitResult();
        });
    });

    addSubjob(decryptJob);
    decryptJob->start();
}
