File indexing completed on 2024-05-12 17:24:09
0001 // SPDX-FileCopyrightText: 2023 Mathis <mbb@kaidan.im> 0002 // SPDX-License-Identifier: LGPL-2.0-or-later 0003 0004 #include "healthhistorymodel.h" 0005 #include <QCoroTask> 0006 #include <QCoroFuture> 0007 #include <QDateTime> 0008 0009 HealthHistoryModel::HealthHistoryModel(QObject *parent) 0010 : QAbstractListModel(parent) 0011 { 0012 } 0013 0014 DB::Plant::Id HealthHistoryModel::plantId() const 0015 { 0016 return m_plantId; 0017 } 0018 0019 void HealthHistoryModel::setPlantId(const DB::Plant::Id plantId) 0020 { 0021 if (plantId == m_plantId) { 0022 return; 0023 } 0024 m_plantId = plantId; 0025 auto future = Database::instance().healthEvents(plantId); 0026 QCoro::connect(std::move(future), this, [this](auto &&healthEvents) { 0027 beginResetModel(); 0028 m_data = healthEvents; 0029 endResetModel(); 0030 }); 0031 Q_EMIT plantIdChanged(); 0032 } 0033 0034 int HealthHistoryModel::rowCount(const QModelIndex &) const 0035 { 0036 return m_data.size(); 0037 } 0038 0039 QHash<int, QByteArray> HealthHistoryModel::roleNames() const 0040 { 0041 return { 0042 {Role::HealthDateRole, "healthDate"}, 0043 {Role::HealthRole, "health"} 0044 }; 0045 } 0046 0047 QVariant HealthHistoryModel::data(const QModelIndex &index, int role) const 0048 { 0049 Q_ASSERT(checkIndex(index, QAbstractItemModel::CheckIndexOption::IndexIsValid)); 0050 0051 const auto event = m_data.at(index.row()); 0052 switch (role){ 0053 case Role::HealthDateRole: 0054 return QDateTime::fromSecsSinceEpoch(event.health_date); 0055 case Role::HealthRole: 0056 return event.health; 0057 }; 0058 0059 Q_UNREACHABLE(); 0060 } 0061 0062 void HealthHistoryModel::addHealthEvent(const int health) 0063 { 0064 const int now = QDateTime::currentDateTime().toSecsSinceEpoch(); 0065 Database::instance().addHealthEvent(m_plantId, now, health); 0066 beginInsertRows({}, m_data.size(), m_data.size()); 0067 m_data.emplace_back(now, health); 0068 endInsertRows(); 0069 }