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

0001 // SPDX-FileCopyrightText: 2023 Joshua Goins <josh@redstrate.com>
0002 // SPDX-License-Identifier: GPL-3.0-only
0003 
0004 #include "featuredtagsmodel.h"
0005 
0006 #include "abstractaccount.h"
0007 #include "accountmanager.h"
0008 #include "relationship.h"
0009 
0010 using namespace Qt::StringLiterals;
0011 
0012 FeaturedTagsModel::FeaturedTagsModel(QObject *parent)
0013     : QAbstractListModel(parent)
0014 {
0015 }
0016 
0017 QString FeaturedTagsModel::accountId() const
0018 {
0019     return m_accountId;
0020 }
0021 
0022 void FeaturedTagsModel::setAccountId(const QString &accountId)
0023 {
0024     if (accountId == m_accountId || accountId.isEmpty()) {
0025         return;
0026     }
0027     m_accountId = accountId;
0028     Q_EMIT accountIdChanged();
0029 
0030     fill();
0031 }
0032 
0033 QVariant FeaturedTagsModel::data(const QModelIndex &index, int role) const
0034 {
0035     Q_ASSERT(checkIndex(index, QAbstractItemModel::CheckIndexOption::IndexIsValid));
0036 
0037     const auto &tag = m_tags[index.row()];
0038 
0039     switch (role) {
0040     case NameRole:
0041         return tag;
0042     default:
0043         return {};
0044     }
0045 }
0046 
0047 int FeaturedTagsModel::rowCount(const QModelIndex &parent) const
0048 {
0049     return parent.isValid() ? 0 : m_tags.size();
0050 }
0051 
0052 QHash<int, QByteArray> FeaturedTagsModel::roleNames() const
0053 {
0054     return {
0055         {NameRole, "name"},
0056     };
0057 }
0058 
0059 void FeaturedTagsModel::fill()
0060 {
0061     const auto account = AccountManager::instance().selectedAccount();
0062 
0063     account->get(account->apiUrl(QStringLiteral("/api/v1/accounts/%1/featured_tags").arg(m_accountId)), true, this, [this](QNetworkReply *reply) {
0064         const auto doc = QJsonDocument::fromJson(reply->readAll());
0065         auto tags = doc.array().toVariantList();
0066 
0067         if (!tags.isEmpty()) {
0068             QVector<QString> fetchedTags;
0069 
0070             std::transform(tags.cbegin(), tags.cend(), std::back_inserter(fetchedTags), [=](const QVariant &value) -> auto {
0071                 return value.toJsonObject()["name"_L1].toString();
0072             });
0073             beginInsertRows({}, m_tags.size(), m_tags.size() + fetchedTags.size() - 1);
0074             m_tags += fetchedTags;
0075             endInsertRows();
0076         }
0077     });
0078 }
0079 
0080 #include "moc_featuredtagsmodel.cpp"