Flesh out UI, provide journey data model
[harbour-pedalo.git] / src / journeymodel.cpp
diff --git a/src/journeymodel.cpp b/src/journeymodel.cpp
new file mode 100644 (file)
index 0000000..18f83c2
--- /dev/null
@@ -0,0 +1,84 @@
+#include "journeymodel.h"
+#include <QDebug>
+
+JourneyModel::JourneyModel(QObject *parent) : QAbstractListModel(parent) {
+    roles[StartRole] = "start";
+    roles[DurationRole] = "duration";
+    roles[OvertookRole] = "overtook";
+    roles[OvertakenByRole] = "overtakenby";
+}
+
+QHash<int, QByteArray> JourneyModel::roleNames() const {
+    return roles;
+}
+
+void JourneyModel::addJourney(const Journey &journey)
+{
+    beginInsertRows(QModelIndex(), rowCount(), rowCount());
+    journeys << journey;
+    endInsertRows();
+}
+
+int JourneyModel::rowCount(const QModelIndex & parent) const {
+    Q_UNUSED(parent)
+    return journeys.count();
+}
+
+QVariant JourneyModel::data(const QModelIndex & index, int role) const {
+    if (index.row() < 0 || index.row() > journeys.count())
+        return QVariant();
+
+    const Journey &journey = journeys[index.row()];
+    if (role == StartRole)
+        return journey.getStart();
+    else if (role == DurationRole)
+        return journey.getDuration();
+    else if (role == OvertookRole)
+        return journey.getOvertook();
+    else if (role == OvertakenByRole)
+        return journey.getOvertakenBy();
+    return QVariant();
+}
+
+void JourneyModel::clear() {
+    journeys.clear();
+}
+
+void JourneyModel::exportToFile(QFile & file) {
+    if (file.open(QIODevice::WriteOnly)) {
+        QTextStream out(&file);
+        for (QList<Journey>::iterator journeyIter = journeys.begin(); journeyIter != journeys.end(); journeyIter++) {
+            out << journeyIter->getStart() << ",";
+            out << journeyIter->getDuration() <<  ",";
+            out << journeyIter->getOvertook() <<  ",";
+            out << journeyIter->getOvertakenBy() << endl;
+        }
+        file.close();
+    }
+}
+
+void JourneyModel::importFromFile(QFile & file) {
+    if (file.open(QIODevice::ReadOnly)) {
+        QTextStream in(&file);
+        while (!in.atEnd()) {
+            QStringList data;
+            quint64 start;
+            qint32 duration = 0;
+            qint32 overtook = 0;
+            qint32 overtakenby = 0;
+
+            data = in.readLine().split(",");
+            if (data.length() == 4) {
+                start = data[0].toLongLong();
+                duration = data[1].toLongLong();
+                overtook = data[2].toLongLong();
+                overtakenby = data[3].toLongLong();
+
+                addJourney(Journey(start, duration, overtook, overtakenby));
+            }
+        }
+        file.close();
+    }
+}
+
+