// SPDX-FileCopyrightText: 2024 g10 Code GmbH
// SPDX-FileContributor: Carl Schwan <carl@carlschwan.eu>
// SPDX-License-Identifier: LGPL-2.1-or-later

#include "rootfoldersmanager.h"
#include "models/storemodel.h"

#include <KSharedConfig>

#include <QDir>
#include <QStandardPaths>
#include <QUuid>

RootFoldersManager::RootFoldersManager(QObject *parent)
    : QObject(parent)
{
    load();
}

void RootFoldersManager::load()
{
    m_rootFolders.clear();
    m_deletedRootFolders.clear();

    auto config = KSharedConfig::openConfig();
    const auto ids = config->groupList();
    for (const auto &id : ids) {
        if (id.startsWith(QStringLiteral("Folder:"))) {
            auto rootFolderConfig = new RootFolderConfig(id);
            m_rootFolders << rootFolderConfig;
        }
    }
}

void RootFoldersManager::save()
{
    for (auto rootFolder : std::as_const(m_rootFolders)) {
        rootFolder->save();
    }

    auto config = KSharedConfig::openConfig();
    for (auto rootFolder : std::as_const(m_deletedRootFolders)) {
        config->deleteGroup(QStringLiteral("Folder: ") + rootFolder->uuid());
    }
    config->sync();
    m_deletedRootFolders.clear();

    Q_EMIT rootFoldersChanged();
}

void RootFoldersManager::markAsDeleted(RootFolderConfig *config)
{
    if (m_rootFolders.contains(config)) {
        m_rootFolders.removeAll(config);
    }

    m_deletedRootFolders << config;
}

RootFolderConfig *RootFoldersManager::addRootFolder(const QString &name, const QString &path)
{
    const auto uuid = QUuid::createUuid().toString(QUuid::WithoutBraces);
    auto config = new RootFolderConfig(QStringLiteral("Folder: ") + uuid);
    config->setPath(path);
    config->setUuid(uuid);
    config->setName(name);
    m_rootFolders << config;
    return config;
}

QList<RootFolderConfig *> RootFoldersManager::rootFolders() const
{
    return m_rootFolders;
}

QString RootFoldersManager::rootFolderName(const QString &dirName) const
{
    for (const auto rootFolder : std::as_const(m_rootFolders)) {
        const auto path = rootFolder->path().split(u'/', Qt::SkipEmptyParts);
        if (path.isEmpty()) {
            continue;
        }
        if (path[path.size() - 1] == dirName) {
            return rootFolder->name();
        }
    }

    return QStringLiteral("Bug");
}
