// SPDX-FileCopyrightText: 2024 g10 code GmbH
// SPDX-FileContributor: Carl Schwan <carl.schwan@gnupg.com>
// SPDX-License-Identifier: LGPL-2.0-or-later

#include "ewsmessagedispatcher.h"
#include "ews/ewscreateitemrequest.h"

#include <KLocalizedString>

using namespace Qt::StringLiterals;

EWSMessageDispatcher::EWSMessageDispatcher(QObject *parent)
    : MessageDispatcher(parent)
{
}

void EWSMessageDispatcher::dispatch(const KMime::Message::Ptr &message, const QString &fromEmail, const QString &mailId)
{
    const QByteArray mimeContent = message->encodedContent(true);

    EwsItem item;
    item.setType(EwsItemTypeMessage);
    item.setField(EwsItemFieldMimeContent, mimeContent);

    auto createItemRequest = new EwsCreateItemRequest(fromEmail);
    createItemRequest->setMessageDisposition(EwsMessageDisposition::EwsDispSendAndSaveCopy);
    createItemRequest->setSavedFolderId(EwsId{EwsDistinguishedId::EwsDIdSentItems});
    createItemRequest->setItems({item});

    connect(createItemRequest, &KJob::result, this, [this, createItemRequest, mailId](KJob *) {
        const auto responses = createItemRequest->responses();
        if (responses.size() > 0 && responses.at(0).isSuccess()) {
            Q_EMIT sentSuccessfully(mailId);
        } else if (responses.isEmpty()) {
            Q_EMIT errorOccurred(mailId, i18n("No response from EWS server."));
        } else {
            Q_EMIT errorOccurred(mailId, responses.at(0).responseMessage());
        }
    });

    createItemRequest->start();
}
