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

#include "draftmanager.h"

#include <QDir>
#include <QStandardPaths>

#include "editor_debug.h"

DraftManager::DraftManager(bool testMode)
    : m_testMode(testMode)
{
    const QDir directory(draftDirectory(testMode));
    const auto entries = directory.entryList(QDir::Files);

    for (const QString &entry : entries) {
        Draft draft(draftDirectory() + entry);
        if (draft.isValid()) {
            m_drafts << draft;
        } else {
            qFatal(EDITOR_LOG) << "File does not exist or is not readable" << entry;
        }
    }
}

QString DraftManager::draftDirectory(bool testMode)
{
    if (testMode) {
        static const QString path = QStandardPaths::writableLocation(QStandardPaths::TempLocation) + QLatin1String("/gpgol-server/draft/");
        return path;
    } else {
        static const QString path = QStandardPaths::writableLocation(QStandardPaths::GenericDataLocation) + QLatin1String("/gpgol-server/draft/");
        return path;
    }
}

QString DraftManager::autosaveDirectory(bool testMode)
{
    if (testMode) {
        static const QString path = QStandardPaths::writableLocation(QStandardPaths::TempLocation) + QLatin1String("/gpgol-server/autosave/");
        return path;
    } else {
        static const QString path = QStandardPaths::writableLocation(QStandardPaths::GenericDataLocation) + QLatin1String("/gpgol-server/autosave/");
        return path;
    }
}

DraftManager &DraftManager::self(bool testMode)
{
    static DraftManager s_draftManager(testMode);
    return s_draftManager;
}

QList<Draft> DraftManager::drafts() const
{
    return m_drafts;
}

QJsonArray DraftManager::toJson() const
{
    if (m_drafts.isEmpty()) {
        return {};
    }

    QJsonArray array;
    std::transform(m_drafts.cbegin(), m_drafts.cend(), std::back_inserter(array), [](const auto draft) {
        return draft.toJson();
    });
    return array;
}

bool DraftManager::remove(const Draft &draft)
{
    auto it = std::find(m_drafts.begin(), m_drafts.end(), draft);
    if (it == m_drafts.end()) {
        return false;
    }

    bool ok = it->remove();
    m_drafts.erase(it);
    return ok;
}

Draft DraftManager::draftById(const QByteArray &draftId)
{
    return Draft(draftDirectory() + QString::fromUtf8(draftId));
}
