File indexing completed on 2024-04-21 04:41:38

0001 /*
0002     SPDX-FileCopyrightText: 2019 Volker Krause <vkrause@kde.org>
0003 
0004     SPDX-License-Identifier: LGPL-2.0-or-later
0005 */
0006 
0007 #ifndef EXAMPLEUTIL_H
0008 #define EXAMPLEUTIL_H
0009 
0010 #include <KPublicTransport/Journey>
0011 #include <KPublicTransport/JourneyQueryModel>
0012 #include <KPublicTransport/Location>
0013 #include <KPublicTransport/LocationQueryModel>
0014 #include <KPublicTransport/Stopover>
0015 #include <KPublicTransport/StopoverQueryModel>
0016 
0017 #include <QDebug>
0018 #include <QFile>
0019 #include <QJsonArray>
0020 #include <QJsonDocument>
0021 #include <QObject>
0022 #include <QUrl>
0023 
0024 class ExampleUtil : public QObject
0025 {
0026     Q_OBJECT
0027 public:
0028     Q_INVOKABLE void saveTo(QObject *model, const QUrl &fileName)
0029     {
0030         QFile f(fileName.toLocalFile());
0031         if (!f.open(QFile::WriteOnly)) {
0032             qWarning() << f.errorString() << fileName;
0033             return;
0034         }
0035 
0036         using namespace KPublicTransport;
0037 
0038         if (qobject_cast<JourneyQueryModel*>(model)) {
0039             f.write(QJsonDocument(Journey::toJson(qobject_cast<JourneyQueryModel*>(model)->journeys())).toJson());
0040         } else if (qobject_cast<StopoverQueryModel*>(model)) {
0041             f.write(QJsonDocument(Stopover::toJson(qobject_cast<StopoverQueryModel*>(model)->departures())).toJson());
0042         } else if (qobject_cast<LocationQueryModel*>(model)) {
0043             f.write(QJsonDocument(Location::toJson(qobject_cast<LocationQueryModel*>(model)->locations())).toJson());
0044         }
0045     }
0046 
0047     Q_INVOKABLE QString locationIds(const QVariant &v)
0048     {
0049         using namespace KPublicTransport;
0050 
0051         const auto loc = v.value<Location>();
0052         const auto ids = loc.identifiers();
0053         QStringList l;
0054         l.reserve(ids.size());
0055         for (auto it = ids.begin(); it != ids.end(); ++it) {
0056             l.push_back(it.key() + QLatin1String(": ") + it.value());
0057         }
0058         return l.join(QLatin1String(", "));
0059     }
0060 };
0061 
0062 #endif // EXAMPLEUTIL_H