// SPDX-FileCopyrightText: 2023 g10 code GmbH
// SPDX-Contributor: Carl Schwan <carl.schwan@gnupg.com>
// SPDX-License-Identifier: GPL-2.0-or-later

#include "draft.h"

#include <QFile>

#include "editor_debug.h"

using namespace Qt::Literals::StringLiterals;

Draft::Draft(const QString &localUrl)
    : m_localUrl(localUrl)
    , m_fileInfo(m_localUrl)
{
}

bool Draft::isValid() const
{
    return m_fileInfo.exists() && m_fileInfo.isReadable();
}

QJsonObject Draft::toJson() const
{
    return {
        {"id"_L1, m_fileInfo.fileName()},
        {"url"_L1, m_localUrl},
        {"last_modification"_L1, lastModified().toSecsSinceEpoch()},
    };
}

QString Draft::localUrl() const
{
    return m_localUrl;
}

QDateTime Draft::lastModified() const
{
    return m_fileInfo.lastModified();
}

bool Draft::remove()
{
    QFile file(m_fileInfo.filePath());
    if (!file.exists()) {
        qCWarning(EDITOR_LOG) << "File doesn't exist anymore.";
        return false;
    }
    return file.remove();
}

KMime::Message::Ptr Draft::mime() const
{
    Q_ASSERT(isValid()); // should be checked by the caller

    QFile file(m_fileInfo.filePath());

    if (!file.open(QIODeviceBase::ReadOnly)) {
        qFatal() << "Can open file" << m_fileInfo.filePath();
    }

    KMime::Message::Ptr message(new KMime::Message());
    message->setContent(KMime::CRLFtoLF(file.readAll()));
    message->assemble();

    return message;
}
