File indexing completed on 2024-05-12 05:04:10

0001 // SPDX-FileCopyrightText: 2023 Joshua Goins <josh@redstrate.com>
0002 // SPDX-License-Identifier: GPL-3.0-or-later
0003 
0004 #include "rulesmodel.h"
0005 
0006 using namespace Qt::Literals::StringLiterals;
0007 
0008 RulesModel::RulesModel(QObject *parent)
0009     : QAbstractListModel(parent)
0010 {
0011 }
0012 
0013 QVariant RulesModel::data(const QModelIndex &index, int role) const
0014 {
0015     Q_ASSERT(checkIndex(index, QAbstractItemModel::CheckIndexOption::IndexIsValid));
0016 
0017     const auto &announcement = m_rules[index.row()];
0018 
0019     switch (role) {
0020     case IdRole:
0021         return announcement.id;
0022     case TextRole:
0023         return announcement.text;
0024     default:
0025         return {};
0026     }
0027 }
0028 
0029 bool RulesModel::loading() const
0030 {
0031     return m_loading;
0032 }
0033 
0034 void RulesModel::setLoading(bool loading)
0035 {
0036     if (m_loading == loading) {
0037         return;
0038     }
0039     m_loading = loading;
0040     Q_EMIT loadingChanged();
0041 }
0042 
0043 AbstractAccount *RulesModel::account() const
0044 {
0045     return m_account;
0046 }
0047 
0048 void RulesModel::setAccount(AbstractAccount *account)
0049 {
0050     if (m_account == account) {
0051         return;
0052     }
0053     m_account = account;
0054     Q_EMIT accountChanged();
0055 
0056     fill();
0057 }
0058 
0059 int RulesModel::rowCount(const QModelIndex &parent) const
0060 {
0061     return parent.isValid() ? 0 : m_rules.size();
0062 }
0063 
0064 QHash<int, QByteArray> RulesModel::roleNames() const
0065 {
0066     return {{IdRole, "id"}, {TextRole, "text"}};
0067 }
0068 
0069 void RulesModel::fill()
0070 {
0071     if (m_loading) {
0072         return;
0073     }
0074     setLoading(true);
0075 
0076     m_account->get(m_account->apiUrl(QStringLiteral("/api/v1/instance/rules")), false, this, [this](QNetworkReply *reply) {
0077         const auto doc = QJsonDocument::fromJson(reply->readAll());
0078         auto rules = doc.array().toVariantList();
0079 
0080         if (!rules.isEmpty()) {
0081             QList<Rule> fetchedRules;
0082 
0083             std::transform(rules.cbegin(), rules.cend(), std::back_inserter(fetchedRules), [=](const QVariant &value) -> auto {
0084                 return fromSourceData(value.toJsonObject());
0085             });
0086             beginInsertRows({}, m_rules.size(), m_rules.size() + fetchedRules.size() - 1);
0087             m_rules += fetchedRules;
0088             endInsertRows();
0089         }
0090 
0091         setLoading(false);
0092     });
0093 }
0094 
0095 RulesModel::Rule RulesModel::fromSourceData(const QJsonObject &object) const
0096 {
0097     Rule rule;
0098     rule.id = object["id"_L1].toString();
0099     rule.text = object["text"_L1].toString();
0100 
0101     return rule;
0102 }
0103 
0104 #include "moc_rulesmodel.cpp"