// 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"

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) {
            return; // error propagation taken care already by KCompositeJob
        }

        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) {
                return; // error propagation taken care already by KCompositeJob
            }

            emitResult();
        });
    });

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