/*
   SPDX-FileCopyrightText: 2025-2026 Laurent Montel <montel@kde.org>

   SPDX-License-Identifier: GPL-2.0-or-later
*/
#include "checkfoldersizeaccountfilterproxymodel.h"
#include <Akonadi/Collection>
#include <Akonadi/CollectionStatistics>
#include <Akonadi/EntityTreeModel>

CheckFolderSizeAccountFilterProxyModel::CheckFolderSizeAccountFilterProxyModel(QObject *parent)
    : TextAddonsWidgets::SortFilterProxyModelBase{parent}
{
    setRecursiveFilteringEnabled(true);
    setFilterCaseSensitivity(Qt::CaseInsensitive);
    setSortRole(Qt::DisplayRole);
    setSortCaseSensitivity(Qt::CaseSensitive);
    setSortLocaleAware(true);
}

CheckFolderSizeAccountFilterProxyModel::~CheckFolderSizeAccountFilterProxyModel() = default;

bool CheckFolderSizeAccountFilterProxyModel::filterAcceptsRow(int source_row, const QModelIndex &source_parent) const
{
    const auto collection = source_parent.data(Akonadi::EntityTreeModel::CollectionRole).value<Akonadi::Collection>();
    const Akonadi::CollectionStatistics statistics = collection.statistics();
    switch (mFolderSize) {
    case FolderSize::MoreThan100K:
        if (statistics.size() < 100000) {
            return false;
        }
        break;
    case FolderSize::MoreThan1M:
        if (statistics.size() < 1000000) {
            return false;
        }
        break;
    case FolderSize::MoreThan10M:
        if (statistics.size() < 10000000) {
            return false;
        }
        break;
    case FolderSize::All:
    case FolderSize::Unknown:
        break;
    }
    const QModelIndex sourceIndex = sourceModel()->index(source_row, 0, source_parent);
    const QString name = sourceIndex.data().toString();
    if (contains(name)) {
        return true;
    }
    return false;
}

CheckFolderSizeAccountFilterProxyModel::FolderSize CheckFolderSizeAccountFilterProxyModel::folderSize() const
{
    return mFolderSize;
}

void CheckFolderSizeAccountFilterProxyModel::setFolderSize(const FolderSize &newFolderSize)
{
    if (mFolderSize != newFolderSize) {
#if QT_VERSION >= QT_VERSION_CHECK(6, 10, 0)
        beginFilterChange();
#endif
        mFolderSize = newFolderSize;
#if QT_VERSION >= QT_VERSION_CHECK(6, 10, 0)
        endFilterChange(QSortFilterProxyModel::Direction::Rows);
#else
        invalidateFilter();
#endif
    }
}

#include "moc_checkfoldersizeaccountfilterproxymodel.cpp"
