18f83c2e68b58e0c0a9be7f60f67e5faf7f5421b
[harbour-pedalo.git] / src / journeymodel.cpp
1 #include "journeymodel.h"
2 #include <QDebug>
3
4 JourneyModel::JourneyModel(QObject *parent) : QAbstractListModel(parent) {
5 roles[StartRole] = "start";
6 roles[DurationRole] = "duration";
7 roles[OvertookRole] = "overtook";
8 roles[OvertakenByRole] = "overtakenby";
9 }
10
11 QHash<int, QByteArray> JourneyModel::roleNames() const {
12 return roles;
13 }
14
15 void JourneyModel::addJourney(const Journey &journey)
16 {
17 beginInsertRows(QModelIndex(), rowCount(), rowCount());
18 journeys << journey;
19 endInsertRows();
20 }
21
22 int JourneyModel::rowCount(const QModelIndex & parent) const {
23 Q_UNUSED(parent)
24 return journeys.count();
25 }
26
27 QVariant JourneyModel::data(const QModelIndex & index, int role) const {
28 if (index.row() < 0 || index.row() > journeys.count())
29 return QVariant();
30
31 const Journey &journey = journeys[index.row()];
32 if (role == StartRole)
33 return journey.getStart();
34 else if (role == DurationRole)
35 return journey.getDuration();
36 else if (role == OvertookRole)
37 return journey.getOvertook();
38 else if (role == OvertakenByRole)
39 return journey.getOvertakenBy();
40 return QVariant();
41 }
42
43 void JourneyModel::clear() {
44 journeys.clear();
45 }
46
47 void JourneyModel::exportToFile(QFile & file) {
48 if (file.open(QIODevice::WriteOnly)) {
49 QTextStream out(&file);
50 for (QList<Journey>::iterator journeyIter = journeys.begin(); journeyIter != journeys.end(); journeyIter++) {
51 out << journeyIter->getStart() << ",";
52 out << journeyIter->getDuration() << ",";
53 out << journeyIter->getOvertook() << ",";
54 out << journeyIter->getOvertakenBy() << endl;
55 }
56 file.close();
57 }
58 }
59
60 void JourneyModel::importFromFile(QFile & file) {
61 if (file.open(QIODevice::ReadOnly)) {
62 QTextStream in(&file);
63 while (!in.atEnd()) {
64 QStringList data;
65 quint64 start;
66 qint32 duration = 0;
67 qint32 overtook = 0;
68 qint32 overtakenby = 0;
69
70 data = in.readLine().split(",");
71 if (data.length() == 4) {
72 start = data[0].toLongLong();
73 duration = data[1].toLongLong();
74 overtook = data[2].toLongLong();
75 overtakenby = data[3].toLongLong();
76
77 addJourney(Journey(start, duration, overtook, overtakenby));
78 }
79 }
80 file.close();
81 }
82 }
83
84