// SPDX-FileCopyrightText: 2015-2017 Krzysztof Nowicki <krissn@op.pl>
// SPDX-FileCopyrightText: 2023 Carl Schwan <carl@carlschwan.eu>
//
// SPDX-License-Identifier: LGPL-2.0-or-later

#include "ewsmailfactory.h"

#include <KLocalizedString>

#include "ewsitem.h"
#include "ewspropertyfield.h"
#include "ewsserverversion.h"

static const EwsPropertyField propPidMessageFlags(0x0e07, EwsPropTypeInteger);

void startSoapDocument(QXmlStreamWriter &writer)
{
    writer.writeStartDocument();

    writer.writeNamespace(soapEnvNsUri, QStringLiteral("soap"));
    writer.writeNamespace(ewsMsgNsUri, QStringLiteral("m"));
    writer.writeNamespace(ewsTypeNsUri, QStringLiteral("t"));

    // SOAP Envelope
    writer.writeStartElement(soapEnvNsUri, QStringLiteral("Envelope"));

    // SOAP Header
    writer.writeStartElement(soapEnvNsUri, QStringLiteral("Header"));
    EwsServerVersion::ewsVersion2007Sp1.writeRequestServerVersion(writer);
    writer.writeEndElement();

    // SOAP Body
    writer.writeStartElement(soapEnvNsUri, QStringLiteral("Body"));
}

void endSoapDocument(QXmlStreamWriter &writer)
{
    // End SOAP Body
    writer.writeEndElement();

    // End SOAP Envelope
    writer.writeEndElement();

    writer.writeEndDocument();
}

QString EwsMailFactory::create(const KMime::Message::Ptr &message)
{
    const QByteArray mimeContent = message->encodedContent(true);

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

    QString reqString;
    QXmlStreamWriter writer(&reqString);

    startSoapDocument(writer);

    writer.writeStartElement(ewsMsgNsUri, QStringLiteral("CreateItem"));

    writer.writeAttribute(QStringLiteral("MessageDisposition"), QStringLiteral("SendOnly"));

    writer.writeStartElement(ewsMsgNsUri, QStringLiteral("Items"));
    item.write(writer);
    writer.writeEndElement();

    writer.writeEndElement();

    endSoapDocument(writer);

    return reqString;
}

#include "moc_ewsmailfactory.cpp"
