// SPDX-FileCopyrightText: 2024 g10 Code GmbH
// SPDX-FileContributor: Carl Schwan <carl.schwan@gnupg.com>
// SPDX-License-Identifier: GPL-3.0-or-later

#pragma once

#include <QAbstractListModel>
#include <QSortFilterProxyModel>

#include <QGpgME/KeyListJob>
#include <gpgme++/keylistresult.h>

#include "userinfo.h"

class UsersListModel : public QAbstractListModel
{
    Q_OBJECT

public:
    /// Extra roles for filtering
    enum ExtraRow {
        NameRole = Qt::UserRole + 1,
    };

    explicit UsersListModel(const QList<QByteArray> &recipients, QObject *parent = nullptr);
    ~UsersListModel() override;

    QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const override;
    bool setData(const QModelIndex &index, const QVariant &value, int role) override;
    int rowCount(const QModelIndex &parent) const override;
    Qt::ItemFlags flags(const QModelIndex &index) const override;

    std::vector<UserInfo> users() const;

Q_SIGNALS:
    void finishedKeysFetching();
    void errorOccurred(const QString &message);

private:
    void generateUserList();
    void slotUserListFetched(const GpgME::KeyListResult &result,
                             const std::vector<GpgME::Key> &keys,
                             const QString &auditLogAsHtml,
                             const GpgME::Error &auditLogError);
    void slotRecipientsFetched(const GpgME::KeyListResult &result, const std::vector<GpgME::Key> &keys, const QStringList &recipients);

    std::vector<UserInfo> m_users;
    const QList<QByteArray> m_recipients;
};

/// Sort filter proxy model for the user lists
class FilterUsersListModel : public QSortFilterProxyModel
{
    Q_OBJECT

public:
    explicit FilterUsersListModel(QObject *parent = nullptr);
    ~FilterUsersListModel() override;

    bool filterAcceptsRow(int sourceRow, const QModelIndex &sourceParent) const override;

    bool showOnlyValidUser() const;
    void setShowOnlyValidUser(bool state);

private:
    bool m_showOnlyValidUser = true;
    QString m_nameFilter;
};
