summaryrefslogtreecommitdiff
path: root/src/model/Sport.cpp
blob: a0ca6494ffadde67e104d44ee85fd6252a129c41 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
#include "Sport.h"
#include "Competitor.h"

// categories
#include <QNetworkReply>
#include <qlogging.h>
#include <qobject.h>
#include <set>

// sorting and filtering
#include <map>
#include <algorithm>
#include <regex>

// float to string formatting
#include <iostream>
#include <iomanip>

#include <QJsonObject>
#include <QJsonArray>
#include <QJsonValueRef>
#include <QString>

namespace {
  const QString &k_requestUrl = "https://sph-s-api.olympics.com/summer/schedules/api/ENG/schedule/discipline/";
}

SportModel::SportModel(QObject *parent) : QAbstractListModel(parent) {
}

int SportModel::rowCount(const QModelIndex &parent) const {
  Q_UNUSED(parent);
  return m_sportList.size();
}

QVariant SportModel::data(const QModelIndex &index, int role) const {
  if (index.isValid() && index.row() >= 0 && index.row() < m_sportList.size()) {
    EventInfo *event = m_sportList[index.row()];

    switch ((Role) role) {
      case EventName:
        return event->eventName();

      case Competitors:
        return event->competitors();
    }
  }

  return {};
}


QHash<int, QByteArray> SportModel::roleNames() const {
  QHash<int, QByteArray> names;
  names[EventName] = "eventName";
  names[Competitors] = "competitors";

  return names;
}

QString SportModel::discipline() const {
  return m_discipline;
}

void SportModel::setDiscipline(const QString &discipline) {
  m_discipline = discipline;
}


void SportModel::request(QString discipline) {
  m_discipline = discipline;
  m_reply = m_networkManager.get(QNetworkRequest( k_requestUrl + m_discipline));
  qDebug() << m_reply;
  connect(m_reply, &QNetworkReply::finished, this, &SportModel::parseData);
}

void SportModel::parseData() {

    if (m_reply->error() == QNetworkReply::NoError) {
      beginResetModel();
      qDeleteAll(m_sportList);
      m_sportList.clear();



      QByteArray strReply = m_reply->readAll();

      //parse json
      // qDebug() << "Response:" << strReply;
      QJsonDocument jsonDocument = QJsonDocument::fromJson(strReply);

      QJsonArray sports = jsonDocument["units"].toArray();
      for (const auto &sport : sports) {
        QJsonObject entry = sport.toObject();

        EventInfo *event = new EventInfo(this);
        event->setEventName(entry["eventUnitName"].toString());

        QList<QString> competitors;
        for (const auto &competitor : entry["competitors"].toArray()) {
          competitors << competitor.toObject()["name"].toString();
        }
        event->setCompetitors(competitors);

        qDebug() << entry["eventUnitName"].toString();
        m_sportList << event;
      }
      endResetModel();
    }
}

// QJsonArray filter function, provide with input array and evaluation function
QJsonArray filter(QJsonArray input, function<bool (QJsonObject)> eval) {
    QJsonArray output;

    for (const QJsonValueRef &elemRef :input) {
        QJsonObject elem = elemRef.toObject();
        if(eval(elem)) {
            output.append(elem);
        }
    }

    return output;
}

/**
 * @brief Sport::lastName Reduce the full name to the part that is marked in capital letters (probably last name).
 * @param competitors The competitors of one category.
 */
void Sport::lastName(QList<Competitor> &competitors) {
    // validate competitors
    if (competitors.isEmpty()) return;

    for (Competitor comp : competitors) {
        string fullName = comp.getName().toUtf8().constData();

        // regex to identify names, written in CAPS
        regex r("[A-Z']{2,}");
        smatch m;

        regex_search(fullName, m, r);

        // combine found names again
        string lastName = "";
        for (string s : m) lastName = lastName + s + " ";

        // remove last space
        QString name = QString(lastName.substr(0, lastName.size() - 1).c_str());

        // replace competitor name in list
        comp.setName(name);
    }
}

/**
 * @brief Sport::validateDiscipline Validates the discipline object. Checks for the units attribute.
 * @return True, if discipline contains units.
 */
bool Sport::validateDiscipline() {
    return this->discipline.contains("units");
}

/**
 * @brief Sport::getCategories Reads all possible categories (also called units).
 * @return A set of all category names.
 */
set<QString> Sport::getCategories() {
    set<QString> categoryNames;

    if (!validateDiscipline()) return categoryNames;

    // search in each unit for the category (named "eventUnitName")
    for (const QJsonValueRef &unitRef : this->discipline["units"].toArray()) {
        QJsonObject unit = unitRef.toObject();

        // validate unit
        if (!unit.contains("eventUnitName")) continue;

        categoryNames.insert(unit["eventUnitName"].toString());
    }

    return categoryNames;
}

/**
 * @brief Sport::getCompetitorsByCategory Searches for all competitors, who took part in the given category.
 * @param category The category to search in.
 * @return An QJsonArray with all competitors as QJsonValueRef, which can be casted to QJsonObject.
 */
QList<CompetitorWithResults> Sport::getCompetitorsByCategory(QString category) {
    QList<CompetitorWithResults> competitors;

    if (!validateDiscipline()) return competitors;

    for (const QJsonValueRef &unitRef : this->discipline["units"].toArray()) {
        QJsonObject unit = unitRef.toObject();

        // validate unit
        if (!unit.contains("eventUnitName") || !unit.contains("competitors")) continue;

        // search all units with the same category
        if (unit["eventUnitName"].toString().compare(category, Qt::CaseSensitive) != 0) continue;

        // add all competitors from one unit
        for (const QJsonValueRef &compRef : unit["competitors"].toArray()) {
            competitors.push_back(CompetitorWithResults(compRef.toObject()));
        }
    }

    return competitors;
}

/**
 * @brief Sport::getCompetitorsWithMedal Filters all competitors, who have at least one medal. These objects are different from getCompetitorsByCategory !!!
 * @return All competitors, who won at least one medal. Structure of one competitor: {code, name, noc, medals{ME_GOLD, ME_SILVER, ME_BRONZE}}
 */
QList<MedalWinner> Sport::getCompetitorsWithMedal() {
    map<QString, QJsonObject> competitors;

    if (!validateDiscipline()) return QList<MedalWinner>();

    // filter all units, which have medal events
    QJsonArray units = filter(this->discipline["units"].toArray(), [](QJsonObject unit){
        // search all units with Final, Gold or Bronze in their name, because these are the categories with the medal winners
        QString unitName = unit["eventUnitName"].toString();
        return unitName.contains("Bronze", Qt::CaseSensitive)
               || unitName.contains("Gold", Qt::CaseSensitive)
               || unitName.contains("Final", Qt::CaseSensitive);
    });

    for (const QJsonValueRef &unitRef : units) {
        QJsonObject unit = unitRef.toObject();

        // validate unit
        if (!unit.contains("competitors")) continue;

        // filter all competitors, who won medals
        QJsonArray medalComps = filter(unit["competitors"].toArray(), [](QJsonObject comp) {
            if (!comp.contains("results")) return false;

            QString medalType = comp["results"].toObject()["medalType"].toString();
            return !medalType.isEmpty();
        });

        for (const QJsonValueRef &medalCompRef : medalComps) {
            QJsonObject medalComp = medalCompRef.toObject();

            // validate competitor (with medal)
            if (!medalComp.contains("name")
                || !medalComp.contains("results")
                || !medalComp["results"].toObject().contains("medalType")) continue;

            QString name = medalComp["name"].toString();
            QString medalType = medalComp["results"].toObject()["medalType"].toString();

            // check if competitor has other medal(s)
            if (competitors.find(name) == competitors.end()) {
                competitors.insert({name, createCompetitorWithMedals(medalComp)});
            }

            // update the medal count
            QJsonObject updatedMedalCount = QJsonObject(competitors.find(name)->second["medals"].toObject());

            int amount = updatedMedalCount[medalType].toInt() + 1;
            updatedMedalCount.remove(medalType);
            updatedMedalCount.insert(medalType, amount);

            // create new medals QJsonObject and set it in the map
            competitors.find(name)->second["medals"] = updatedMedalCount;
        }
    }

    // convert map to QJsonArray
    QList<MedalWinner> output;
    for (const pair<QString, QJsonObject> &competitor : competitors) {
        output.append(MedalWinner(competitor.second));
    }

    return output;
}

/**
 * @brief Sport::createCompetitorWithMedals Creates a competitor QJsonObject with the following attributes: code, name, noc, medals{ME_GOLD, ME_SILVER, ME_BRONZE}
 * @param comp The original competitor object.
 * @return A competitor object with medal counts.
 */
QJsonObject Sport::createCompetitorWithMedals(QJsonObject comp) {
    // repair competitor if something is missing
    if (!comp.contains("code")) comp.insert("code", "0");
    if (!comp.contains("name")) comp.insert("code", "");
    if (!comp.contains("noc")) comp.insert("code", "");

    // create new competitor QJsonObject and add it to the competitor map
    QJsonObject medals {
        {"ME_GOLD", 0},
        {"ME_SILVER", 0},
        {"ME_BRONZE", 0}
    };

    QJsonObject medalComp {
        {"code", comp["code"].toString()},
        {"name", comp["name"].toString()},
        {"noc", comp["noc"].toString()},
        {"medals", medals}
    };

    return medalComp;
}

/**
 * @brief Sport::filterByName Filter the competitors by name (case insensitive).
 * @param competitors The competitors of one category.
 * @param name The (part of the) name to search for.
 */
void Sport::filterByName(QList<Competitor> &competitors, QString name) {
    filterCompetitors(competitors, name);
}

/**
 * @brief Sport::filterByCountry Filter the competitors by their national olympics comittee (case insensitive, short form).
 * @param competitors The competitors of one category.
 * @param nocShort The (part of the) national olympics comittee short name to search for.
 */
void Sport::filterByCountry(QList<Competitor> &competitors, QString nocShort) {
    filterCompetitors(competitors, nocShort);
}

/**
 * @brief Sport::filterCompetitors Filters the given QJsonArray by comparing the value of a certain attribute with the given filter string.
 * @param competitors The competitors of one category.
 * @param attribute The attribute to filter by.
 * @param filter The string, which should be contained.
 */
void Sport::filterCompetitors(QList<Competitor> &competitors, QString filter) {
    for (qsizetype i = 0; i < competitors.size(); i++) {
        if (competitors.value(i).getNOC().contains(filter)) {
            competitors.remove(i);
            i--;
        }
    }
}

/**
 * @brief Sport::sortByName Sort the competitors by their name (alphabetical, ascending).
 * @param competitors The competitors of one category.
 */
void Sport::sortByName(QList<Competitor> &competitors) {
    if (competitors.isEmpty()) return;
    sort(competitors.begin(), competitors.end(), Competitor::compareName);
}

/**
 * @brief Sport::sortByCountry Sort the competitors by their national olympic comittee short name (alphabetical, ascending).
 * @param competitors The competitors of one category.
 */
void Sport::sortByCountry(QList<Competitor> &competitors) {
    if (competitors.isEmpty()) return;
    sort(competitors.begin(), competitors.end(), Competitor::compareNOC);
}

/**
 * @brief Sport::sortByResult Sort the competitors by their results in one specific category (numerical, ascending).
 * @param competitors The competitors of one category.
 */
void Sport::sortByResult(QList<CompetitorWithResults> &competitors) {
    if (competitors.isEmpty()) return;
    sort(competitors.begin(), competitors.end(), CompetitorWithResults::compare);
}

/**
 * @brief Sport::sortByMedals Sort the competitors by their medal amounts in one specific category (numerical, ascending).
 * @param competitors The competitors of one category.
 */
void Sport::sortByMedals(QList<MedalWinner> &competitors) {
    if (competitors.isEmpty()) return;
    sort(competitors.begin(), competitors.end(), MedalWinner::compare);
}

/**
 * @brief Sport::reverseOrder Reverses the order of the competitors.
 * @param competitors The competitors of one category.
 */
void Sport::reverseOrder(QList<Competitor> &competitors) {
    int iterations = competitors.size() / 2; // automatically rounds down

    for (int i = 0; i < iterations; i++) {
        Competitor temp = competitors.value(i);
        competitors.replace(i, competitors.value(competitors.size() - 1 - i));
        competitors.replace(competitors.size() - 1 - i, temp);
    }
}

/**
 * @brief Sport::addRelativeToFirst Adds a relative value to the result of all competitors. Relative to the first competitor in the QJsonArray.
 * Stores the statistic in obj->results->stat for each competitor.
 * @param competitors The competitors of one category.
 */
void Sport::addRelativeToFirst(QList<CompetitorWithResults> &competitors) {
    if (competitors.isEmpty()) return;

    QString reference = competitors.value(0).getMark();

    for (CompetitorWithResults comp : competitors) {
        QString results = comp.getMark();

        // format relative float value to string with 2 digits after decimal point and sign
        stringstream sstream;
        sstream << fixed << setprecision(2) << calcRelativeStat(reference, results["mark"].toString());
        QString stat(sstream.str().c_str());
        stat.append("%");
        if (stat.at(0).isNumber()) stat = QString("+").append(stat);

        comp.setStatistic(stat);
    }

}

/**
 * @brief Sport::calcRelativeStat Calculates the relative deviation of val from ref in percent.
 * @param ref The reference value.
 * @param val The value to calculate the deviation from.
 * @return The deviation from ref to val in percent.
 */
float Sport::calcRelativeStat(QString ref, QString val) {
    // check if the value is not a time
    if (!ref.contains(":") && !val.contains(":")) {
        float fRef = ref.toFloat();

        if (fRef == 0) return 0.0;
        return ((val.toFloat() * 100)/ fRef) - 100;
    }

    regex r("\\d+");
    smatch mref, mval;
    string sref = ref.toUtf8().constData();
    string sval = val.toUtf8().constData();

    regex_search(sref, mref, r);
    regex_search(sval, mval, r);

    float timeRef = stof(mref.str(1)) * 60 * 100 + stof(mref.str(2)) * 100 + stof(mref.str(3));
    float timeVal = stof(mval.str(1)) * 60 * 100 + stof(mval.str(2)) * 100 + stof(mval.str(3));

    return ((timeVal * 100) / timeRef) - 100;
}