File indexing completed on 2024-12-01 05:20:05

0001 /**
0002  * SPDX-FileCopyrightText: 2019 Nicolas Fella <nicolas.fella@gmx.de>
0003  *
0004  * SPDX-License-Identifier: GPL-2.0-only OR GPL-3.0-only OR LicenseRef-KDE-Accepted-GPL
0005  */
0006 
0007 #include "locationcachemodel.h"
0008 
0009 #include <QDateTime>
0010 #include <QDebug>
0011 #include <QJsonDocument>
0012 #include <QJsonObject>
0013 #include <QStandardPaths>
0014 
0015 LocationCacheModel::LocationCacheModel(QObject *parent)
0016     : QAbstractListModel(parent)
0017     , m_locationCacheFile(QStandardPaths::writableLocation(QStandardPaths::CacheLocation) + QStringLiteral("/locations.cache"))
0018     , m_cachedLocationsJson()
0019 {
0020     if (!m_locationCacheFile.open(QIODevice::ReadWrite)) {
0021         qWarning() << "Could not open location cache file" << m_locationCacheFile.fileName();
0022     }
0023 
0024     loadLocationsFromCache();
0025 }
0026 
0027 void LocationCacheModel::addCachedLocation(const KPublicTransport::Location location)
0028 {
0029     if (m_cachedLocations.contains(QVariant::fromValue(location))) {
0030         return;
0031     }
0032 
0033     m_cachedLocations.append(QVariant::fromValue(location));
0034     m_cachedLocationsJson.append(KPublicTransport::Location::toJson(location));
0035 
0036     QJsonObject obj;
0037     obj[QStringLiteral("version")] = 1;
0038     obj[QStringLiteral("locations")] = m_cachedLocationsJson;
0039 
0040     QJsonDocument doc(obj);
0041 
0042     m_locationCacheFile.resize(0);
0043     m_locationCacheFile.write(doc.toJson());
0044     m_locationCacheFile.flush();
0045 }
0046 
0047 void LocationCacheModel::loadLocationsFromCache()
0048 {
0049     m_cachedLocationsJson = QJsonDocument::fromJson(m_locationCacheFile.readAll()).object()[QStringLiteral("locations")].toArray();
0050 
0051     for (const QJsonValue &val : qAsConst(m_cachedLocationsJson)) {
0052         m_cachedLocations.append(QVariant::fromValue(KPublicTransport::Location::fromJson(val.toObject())));
0053     }
0054 }
0055 
0056 QVariant LocationCacheModel::data(const QModelIndex &index, int role) const
0057 {
0058     Q_ASSERT(index.row() >= 0);
0059     Q_ASSERT(index.row() <= m_cachedLocations.count());
0060 
0061     if (role == Qt::UserRole + 1) {
0062         return m_cachedLocations[index.row()];
0063     }
0064 
0065     return QStringLiteral("deadbeef");
0066 }
0067 
0068 int LocationCacheModel::rowCount(const QModelIndex &parent) const
0069 {
0070     Q_UNUSED(parent);
0071     return m_cachedLocations.count();
0072 }
0073 
0074 QHash<int, QByteArray> LocationCacheModel::roleNames() const
0075 {
0076     QHash<int, QByteArray> roles;
0077     roles.insert((Qt::UserRole + 1), "location");
0078     return roles;
0079 }