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

#include "models/rootfoldersmodel.h"
#include "rootfolderconfig.h"
#include "rootfoldersmanager.h"

#include <QFileInfo>
#include <QUuid>

#include <KLocalizedString>

RootFoldersModel::RootFoldersModel(RootFoldersManager *manager, QObject *parent)
    : QAbstractListModel(parent)
    , m_manager(manager)
{
}

void RootFoldersModel::load()
{
    beginResetModel();
    m_manager->load();
    m_rootFolders = m_manager->rootFolders();
    endResetModel();
}

QVariant RootFoldersModel::data(const QModelIndex &index, int role) const
{
    Q_ASSERT(checkIndex(index, QAbstractItemModel::CheckIndexOption::IndexIsValid));

    const auto &rootFolder = m_rootFolders[index.row()];

    switch (role) {
    case Qt::DisplayRole:
        return rootFolder->name();
    case Qt::UserRole:
        return QVariant::fromValue(rootFolder);
    }
    return {};
}

bool RootFoldersModel::setData(const QModelIndex &index, const QVariant &data, int role)
{
    Q_ASSERT(checkIndex(index, QAbstractItemModel::CheckIndexOption::IndexIsValid));

    switch (role) {
    case Qt::UserRole:
        m_rootFolders[index.row()] = data.value<RootFolderConfig *>();
        Q_EMIT dataChanged(index, index, {});
        return true;
    }

    return false;
}

int RootFoldersModel::rowCount(const QModelIndex &parent) const
{
    return parent.isValid() ? 0 : m_rootFolders.size();
}

QModelIndex RootFoldersModel::addNewFolder()
{
    const auto size = m_rootFolders.size();
    beginInsertRows({}, size, size);
    m_rootFolders << m_manager->addRootFolder(i18nc("@info:placeholder", "New Store"), {});
    endInsertRows();
    return index(size, 0);
}

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

void RootFoldersModel::slotRemoveFolder(const QModelIndex &index)
{
    Q_ASSERT(checkIndex(index, QAbstractItemModel::CheckIndexOption::IndexIsValid));

    beginRemoveRows({}, index.row(), index.row());
    const auto rootFolder = data(index, Qt::UserRole).value<RootFolderConfig *>();
    m_manager->markAsDeleted(rootFolder);
    m_rootFolders.removeAt(index.row());
    endRemoveRows();
}
