]> git.sesse.net Git - pkanalytics/blob - main.cpp
Tweak formation backdating.
[pkanalytics] / main.cpp
1 #include <QMediaPlayer>
2 #include <QMainWindow>
3 #include <QApplication>
4 #include <QGridLayout>
5 #include <QVideoWidget>
6 #include <QShortcut>
7 #include <QInputDialog>
8 #include <algorithm>
9 #include <string>
10 #include <map>
11 #include <vector>
12 #include <optional>
13 #include <sqlite3.h>
14 #include "mainwindow.h"
15 #include "ui_mainwindow.h"
16 #include "events.h"
17 #include "players.h"
18 #include "formations.h"
19 #include "json.h"
20
21 using namespace std;
22
23 string format_timestamp(uint64_t pos)
24 {
25         int ms = pos % 1000;
26         pos /= 1000;
27         int sec = pos % 60;
28         pos /= 60;
29         int min = pos % 60;
30         int hour = pos / 60;
31
32         char buf[256];
33         snprintf(buf, sizeof(buf), "%d:%02d:%02d.%03d", hour, min, sec, ms);
34         return buf;
35 }
36
37 MainWindow::MainWindow(EventsModel *events, PlayersModel *players,
38                        FormationsModel *offensive_formations, FormationsModel *defensive_formations)
39         : events(events), players(players), offensive_formations(offensive_formations), defensive_formations(defensive_formations)
40 {
41         video = new QMediaPlayer;
42         //video->setSource(QUrl::fromLocalFile("/home/sesse/dev/stats/ultimate.mkv"));
43         video->setSource(QUrl::fromLocalFile("/home/sesse/dev/stats/ultimate-prores.mkv"));
44         video->play();
45
46         ui = new Ui::MainWindow;
47         ui->setupUi(this);
48
49         ui->event_view->setModel(events);
50         ui->event_view->setColumnWidth(1, 150);
51         ui->event_view->setColumnWidth(2, 150);
52         connect(ui->event_view->selectionModel(), &QItemSelectionModel::currentRowChanged,
53                 [this, events](const QModelIndex &current, const QModelIndex &previous) {
54                         uint64_t t = events->get_time(current.row());
55                         if (t != video->position()) {
56                                 video->setPosition(events->get_time(current.row()));
57                         } else {
58                                 // Selection could have changed, so we still need to update.
59                                 // (Just calling setPosition() would not give us the signal
60                                 // in this case.)
61                                 update_ui_from_time(t);
62                         }
63                 });
64
65         ui->player_view->setModel(players);
66         ui->player_view->setColumnWidth(0, 30);
67         ui->player_view->setColumnWidth(1, 20);
68         ui->player_view->horizontalHeader()->setStretchLastSection(true);
69
70         auto formation_changed = [this](const QModelIndex &current, const QModelIndex &previous) {
71                 update_action_buttons(video->position());
72         };
73         ui->offensive_formation_view->setModel(offensive_formations);
74         ui->defensive_formation_view->setModel(defensive_formations);
75         connect(ui->offensive_formation_view->selectionModel(), &QItemSelectionModel::currentRowChanged, formation_changed);
76         connect(ui->defensive_formation_view->selectionModel(), &QItemSelectionModel::currentRowChanged, formation_changed);
77         connect(ui->offensive_formation_view, &QListView::doubleClicked, [this](const QModelIndex &index) {
78                 formation_double_clicked(true, index.row());
79         });
80         connect(ui->defensive_formation_view, &QListView::doubleClicked, [this](const QModelIndex &index) {
81                 formation_double_clicked(false, index.row());
82         });
83
84         connect(video, &QMediaPlayer::positionChanged, [this](uint64_t pos) {
85                 position_changed(pos);
86         });
87
88         video->setVideoOutput(ui->video);
89
90         // It's not really clear whether PgUp should be forwards or backwards,
91         // but mpv does at least up = forwards, so that's probably standard.
92         QShortcut *pgdown = new QShortcut(QKeySequence(Qt::Key_PageDown), this);
93         connect(pgdown, &QShortcut::activated, [this]() { seek(-120000); });
94         QShortcut *pgup = new QShortcut(QKeySequence(Qt::Key_PageUp), this);
95         connect(pgup, &QShortcut::activated, [this]() { seek(120000); });
96
97         // Ugh. Used when Qt messes up and hangs the video.
98         QShortcut *f5 = new QShortcut(QKeySequence(Qt::Key_F5), this);
99         connect(f5, &QShortcut::activated, [this]() {
100                 QVideoWidget *nvw = new QVideoWidget(ui->video->parentWidget());
101                 nvw->setObjectName("video");
102                 nvw->setMinimumSize(QSize(320, 240));
103                 video->setVideoOutput(nvw);
104                 ui->main_grid->replaceWidget(ui->video, nvw);
105                 ui->video = nvw;
106         });
107
108         connect(ui->minus10s, &QPushButton::clicked, [this]() { seek(-10000); });
109         connect(ui->plus10s, &QPushButton::clicked, [this]() { seek(10000); });
110
111         connect(ui->minus2s, &QPushButton::clicked, [this]() { seek(-2000); });
112         connect(ui->plus2s, &QPushButton::clicked, [this]() { seek(2000); });
113
114         // TODO: Would be nice to actually have a frame...
115         connect(ui->minus1f, &QPushButton::clicked, [this]() { seek(-20); });
116         connect(ui->plus1f, &QPushButton::clicked, [this]() { seek(20); });
117
118         connect(ui->play_pause, &QPushButton::clicked, [this]() {
119                 if (playing) {
120                         video->pause();
121                         ui->play_pause->setText("Play (space)");
122                 } else {
123                         video->setPlaybackRate(1.0);
124                         video->play();
125                         ui->play_pause->setText("Pause (space)");
126                 }
127                 playing = !playing;
128
129                 // Needs to be set anew when we modify setText(), evidently.
130                 ui->play_pause->setShortcut(QCoreApplication::translate("MainWindow", "Space", nullptr));
131         });
132
133         connect(ui->player_1, &QPushButton::clicked, [this]() { insert_player_event(0); });
134         connect(ui->player_2, &QPushButton::clicked, [this]() { insert_player_event(1); });
135         connect(ui->player_3, &QPushButton::clicked, [this]() { insert_player_event(2); });
136         connect(ui->player_4, &QPushButton::clicked, [this]() { insert_player_event(3); });
137         connect(ui->player_5, &QPushButton::clicked, [this]() { insert_player_event(4); });
138         connect(ui->player_6, &QPushButton::clicked, [this]() { insert_player_event(5); });
139         connect(ui->player_7, &QPushButton::clicked, [this]() { insert_player_event(6); });
140
141         // Offensive events
142         connect(ui->offense_label, &ClickableLabel::clicked, [this]() { insert_noplayer_event("set_offense"); });
143         connect(ui->catch_, &QPushButton::clicked, [this]() { set_current_event_type("catch"); });
144         connect(ui->throwaway, &QPushButton::clicked, [this, events]() {
145                 EventsModel::Status s = events->get_status_at(video->position());
146                 if (s.attack_state == EventsModel::Status::DEFENSE && s.pull_state == EventsModel::Status::PULL_IN_AIR) {
147                         insert_noplayer_event("pull_oob");
148                 } else {
149                         set_current_event_type("throwaway");
150                 }
151         });
152         connect(ui->drop, &QPushButton::clicked, [this]() { set_current_event_type("drop"); });
153         connect(ui->goal, &QPushButton::clicked, [this]() { set_current_event_type("goal"); });
154         connect(ui->offensive_soft_plus, &QPushButton::clicked, [this]() { set_current_event_type("offensive_soft_plus"); });
155         connect(ui->offensive_soft_minus, &QPushButton::clicked, [this]() { set_current_event_type("offensive_soft_minus"); });
156         connect(ui->pull, &QPushButton::clicked, [this, events]() {
157                 EventsModel::Status s = events->get_status_at(video->position());
158                 if (s.pull_state == EventsModel::Status::SHOULD_PULL) {
159                         set_current_event_type("pull");
160                 } else if (EventsModel::Status::PULL_IN_AIR) {
161                         insert_noplayer_event("pull_landed");
162                 }
163         });
164
165         // Defensive events (TODO add more)
166         connect(ui->interception, &QPushButton::clicked, [this]() { set_current_event_type("interception"); });
167         connect(ui->defense_label, &ClickableLabel::clicked, [this]() { insert_noplayer_event("set_defense"); });
168         connect(ui->their_throwaway, &QPushButton::clicked, [this]() { insert_noplayer_event("their_throwaway"); });
169         connect(ui->their_goal, &QPushButton::clicked, [this]() { insert_noplayer_event("their_goal"); });
170         connect(ui->their_pull, &QPushButton::clicked, [this, events]() {
171                 EventsModel::Status s = events->get_status_at(video->position());
172                 if (s.pull_state == EventsModel::Status::SHOULD_PULL) {
173                         insert_noplayer_event("their_pull");
174                 }
175         });
176         connect(ui->our_defense, &QPushButton::clicked, [this]() { set_current_event_type("defense"); });
177         connect(ui->defensive_soft_plus, &QPushButton::clicked, [this]() { set_current_event_type("defensive_soft_plus"); });
178         connect(ui->defensive_soft_minus, &QPushButton::clicked, [this]() { set_current_event_type("defensive_soft_minus"); });
179
180         // Misc. events
181         connect(ui->substitution, &QPushButton::clicked, [this]() { make_substitution(); });
182         connect(ui->stoppage, &QPushButton::clicked, [this, events]() {
183                 EventsModel::Status s = events->get_status_at(video->position());
184                 if (s.stoppage) {
185                         insert_noplayer_event("restart");
186                 } else {
187                         insert_noplayer_event("stoppage");
188                 }
189         });
190         connect(ui->unknown, &QPushButton::clicked, [this]() { insert_noplayer_event("unknown"); });
191
192         QShortcut *key_delete = new QShortcut(QKeySequence(Qt::Key_Delete), this);
193         connect(key_delete, &QShortcut::activated, [this]() { ui->delete_->animateClick(); });
194         connect(ui->delete_, &QPushButton::clicked, [this]() { delete_current_event(); });
195 }
196
197 void MainWindow::position_changed(uint64_t pos)
198 {
199         ui->timestamp->setText(QString::fromUtf8(format_timestamp(pos)));
200         if (buffered_seek) {
201                 video->setPosition(*buffered_seek);
202                 buffered_seek.reset();
203         }
204         if (!playing) {
205                 video->pause();  // We only played to get a picture.
206         }
207         if (playing) {
208                 QModelIndex row = events->get_last_event_qt(video->position());
209                 ui->event_view->scrollTo(row, QAbstractItemView::PositionAtCenter);
210         }
211         update_ui_from_time(pos);
212 }
213
214 void MainWindow::seek(int64_t delta_ms)
215 {
216         int64_t current_pos = buffered_seek ? *buffered_seek : video->position();
217         uint64_t pos = max<int64_t>(current_pos + delta_ms, 0);
218         buffered_seek = pos;
219         if (!playing) {
220                 video->setPlaybackRate(0.01);
221                 video->play();  // Or Qt won't show the seek.
222         }
223 }
224
225 void MainWindow::insert_player_event(int button_id)
226 {
227         uint64_t t = video->position();
228         vector<int> team = events->sort_team(events->get_team_at(t));
229         if (button_id >= team.size()) {
230                 return;
231         }
232         int player_id = team[button_id];
233
234         EventsModel::Status s = events->get_status_at(t);
235
236         ui->event_view->selectionModel()->blockSignals(true);
237         if (s.attack_state == EventsModel::Status::OFFENSE) {
238                 // TODO: Perhaps not if that player already did the last catch?
239                 ui->event_view->selectRow(events->insert_event(t, player_id, nullopt, "catch"));
240         } else {
241                 ui->event_view->selectRow(events->insert_event(t, player_id, nullopt));
242         }
243         ui->event_view->selectionModel()->blockSignals(false);
244
245         update_ui_from_time(t);
246 }
247
248 void MainWindow::insert_noplayer_event(const string &type)
249 {
250         uint64_t t = video->position();
251
252         ui->event_view->selectionModel()->blockSignals(true);
253         ui->event_view->selectRow(events->insert_event(t, nullopt, nullopt, type));
254         ui->event_view->selectionModel()->blockSignals(false);
255
256         update_ui_from_time(t);
257 }
258
259 void MainWindow::set_current_event_type(const string &type)
260 {
261         QItemSelectionModel *select = ui->event_view->selectionModel();
262         if (!select->hasSelection()) {
263                 return;
264         }
265         int row = select->selectedRows().front().row();  // Should only be one, due to our selection behavior.
266         events->set_event_type(row, type);
267         update_ui_from_time(video->position());
268 }
269
270 void MainWindow::delete_current_event()
271 {
272         QItemSelectionModel *select = ui->event_view->selectionModel();
273         if (!select->hasSelection()) {
274                 return;
275         }
276         int row = select->selectedRows().front().row();  // Should only be one, due to our selection behavior.
277         ui->event_view->selectionModel()->blockSignals(true);
278         events->delete_event(row);
279         ui->event_view->selectionModel()->blockSignals(false);
280         update_ui_from_time(video->position());
281 }
282
283 void MainWindow::make_substitution()
284 {
285         QItemSelectionModel *select = ui->player_view->selectionModel();
286         set<int> new_team;
287         for (QModelIndex row : select->selectedRows()) {
288                 new_team.insert(players->get_player_id(row.row()));
289         }
290         events->set_team_at(video->position(), new_team);
291 }
292
293 void MainWindow::update_ui_from_time(uint64_t t)
294 {
295         update_status(t);
296         update_player_buttons(t);
297         update_action_buttons(t);
298 }
299
300 void MainWindow::update_status(uint64_t t)
301 {
302         EventsModel::Status s = events->get_status_at(t);
303         char buf[256];
304         std::string formation = "Not started";
305         if (s.attack_state == EventsModel::Status::OFFENSE) {
306                 if (s.offensive_formation != 0) {
307                         formation = offensive_formations->get_formation_name_by_id(s.offensive_formation);
308                 } else {
309                         formation = "Offense";
310                 }
311         } else if (s.attack_state == EventsModel::Status::DEFENSE) {
312                 if (s.defensive_formation != 0) {
313                         formation = defensive_formations->get_formation_name_by_id(s.defensive_formation);
314                 } else {
315                         formation = "Defense";
316                 }
317         }
318
319         snprintf(buf, sizeof(buf), "%d–%d | %s | %d passes, %d sec possession",
320                 s.our_score, s.their_score, formation.c_str(), s.num_passes, s.possession_sec);
321         if (s.stoppage_sec > 0) {
322                 char buf2[256];
323                 snprintf(buf2, sizeof(buf2), "%s (plus %d sec stoppage)", buf, s.stoppage_sec);
324                 ui->status->setText(buf2);
325         } else {
326                 ui->status->setText(buf);
327         }
328 }
329
330 void MainWindow::update_player_buttons(uint64_t t)
331 {
332         QPushButton *buttons[] = {
333                 ui->player_1,
334                 ui->player_2,
335                 ui->player_3,
336                 ui->player_4,
337                 ui->player_5,
338                 ui->player_6,
339                 ui->player_7
340         };
341         const char shortcuts[] = "qweasdf";
342         int num_players = 0;
343         for (int player_id : events->sort_team(events->get_team_at(t))) {
344                 QPushButton *btn = buttons[num_players];
345                 string label = players->get_player_name_by_id(player_id) + " (&" + shortcuts[num_players] + ")";
346                 char shortcut[2] = "";
347                 shortcut[0] = toupper(shortcuts[num_players]);
348                 btn->setText(QString::fromUtf8(label));
349                 btn->setShortcut(QCoreApplication::translate("MainWindow", shortcut, nullptr));
350                 btn->setEnabled(true);
351                 if (++num_players == 7) {
352                         break;
353                 }
354         }
355         for (int i = num_players; i < 7; ++i) {
356                 QPushButton *btn = buttons[i];
357                 btn->setText("No player");
358                 btn->setEnabled(false);
359         }
360 }
361
362 void MainWindow::update_action_buttons(uint64_t t)
363 {
364         {
365                 QItemSelectionModel *select = ui->offensive_formation_view->selectionModel();
366                 if (select->hasSelection()) {
367                         int row = select->selectedRows().front().row();  // Should only be one, due to our selection behavior.
368                         ui->offensive_formation->setEnabled(offensive_formations->get_formation_id(row) != -1);
369                 } else {
370                         ui->offensive_formation->setEnabled(false);
371                 }
372         }
373         {
374                 QItemSelectionModel *select = ui->defensive_formation_view->selectionModel();
375                 if (select->hasSelection()) {
376                         int row = select->selectedRows().front().row();  // Should only be one, due to our selection behavior.
377                         ui->defensive_formation->setEnabled(defensive_formations->get_formation_id(row) != -1);
378                 } else {
379                         ui->defensive_formation->setEnabled(false);
380                 }
381         }
382
383         EventsModel::Status s = events->get_status_at(t);
384
385         bool has_selection = false;
386         bool has_selection_with_player = false;
387
388         QItemSelectionModel *select = ui->event_view->selectionModel();
389         if (select->hasSelection()) {
390                 has_selection = true;
391                 int row = select->selectedRows().front().row();  // Should only be one, due to our selection behavior.
392                 has_selection_with_player = events->get_player_id(row).has_value();
393         }
394         ui->delete_->setEnabled(has_selection);
395
396         if (s.stoppage) {
397                 ui->stoppage->setText("Restart (&v)");
398                 ui->stoppage->setShortcut(QCoreApplication::translate("MainWindow", "V", nullptr));
399                 ui->catch_->setEnabled(false);
400                 ui->throwaway->setEnabled(false);
401                 ui->drop->setEnabled(false);
402                 ui->goal->setEnabled(false);
403                 ui->offensive_soft_plus->setEnabled(false);
404                 ui->offensive_soft_minus->setEnabled(false);
405                 ui->pull->setEnabled(false);
406                 ui->interception->setEnabled(false);
407                 ui->their_throwaway->setEnabled(false);
408                 ui->our_defense->setEnabled(false);
409                 ui->their_goal->setEnabled(false);
410                 ui->defensive_soft_plus->setEnabled(false);
411                 ui->defensive_soft_minus->setEnabled(false);
412                 ui->their_pull->setEnabled(false);
413                 return;
414         } else {
415                 ui->stoppage->setText("Stoppage (&v)");
416                 ui->stoppage->setShortcut(QCoreApplication::translate("MainWindow", "V", nullptr));
417         }
418
419         // Defaults for pull-related buttons.
420         ui->pull->setText("Pull (&p)");
421         ui->their_pull->setText("Their pull (&p)");
422         ui->pull->setShortcut(QCoreApplication::translate("MainWindow", "P", nullptr));
423         ui->their_pull->setShortcut(QCoreApplication::translate("MainWindow", "P", nullptr));
424         ui->throwaway->setText("Throwaway (&t)");
425         ui->throwaway->setShortcut(QCoreApplication::translate("MainWindow", "T", nullptr));
426
427         if (s.pull_state == EventsModel::Status::SHOULD_PULL) {
428                 ui->pull->setEnabled(s.attack_state == EventsModel::Status::DEFENSE && has_selection_with_player);
429                 ui->their_pull->setEnabled(s.attack_state == EventsModel::Status::OFFENSE);
430
431                 ui->catch_->setEnabled(false);
432                 ui->throwaway->setEnabled(false);
433                 ui->drop->setEnabled(false);
434                 ui->goal->setEnabled(false);
435                 ui->offensive_soft_plus->setEnabled(false);
436                 ui->offensive_soft_minus->setEnabled(false);
437                 ui->interception->setEnabled(false);
438                 ui->their_throwaway->setEnabled(false);
439                 ui->our_defense->setEnabled(false);
440                 ui->their_goal->setEnabled(false);
441                 ui->defensive_soft_plus->setEnabled(false);
442                 ui->defensive_soft_minus->setEnabled(false);
443                 return;
444         }
445         if (s.pull_state == EventsModel::Status::PULL_IN_AIR) {
446                 if (s.attack_state == EventsModel::Status::DEFENSE) {
447                         ui->pull->setText("Pull landed (&p)");
448                         ui->pull->setShortcut(QCoreApplication::translate("MainWindow", "P", nullptr));
449                         ui->pull->setEnabled(true);
450
451                         ui->throwaway->setText("Pull OOB (&t)");
452                         ui->throwaway->setShortcut(QCoreApplication::translate("MainWindow", "T", nullptr));
453                         ui->throwaway->setEnabled(true);
454                 } else {
455                         ui->pull->setEnabled(false);
456                         ui->throwaway->setEnabled(false);
457                 }
458                 ui->their_pull->setEnabled(false);  // We don't track their pull landings; only by means of catch etc.
459
460                 ui->catch_->setEnabled(false);
461                 ui->drop->setEnabled(false);
462                 ui->goal->setEnabled(false);
463                 ui->offensive_soft_plus->setEnabled(false);
464                 ui->offensive_soft_minus->setEnabled(false);
465                 ui->interception->setEnabled(false);
466                 ui->their_throwaway->setEnabled(false);
467                 ui->our_defense->setEnabled(false);
468                 ui->their_goal->setEnabled(false);
469                 ui->defensive_soft_plus->setEnabled(false);
470                 ui->defensive_soft_minus->setEnabled(false);
471                 return;
472         }
473
474         ui->catch_->setEnabled(s.attack_state == EventsModel::Status::OFFENSE && has_selection_with_player);
475         ui->throwaway->setEnabled(s.attack_state == EventsModel::Status::OFFENSE && has_selection_with_player);
476         ui->drop->setEnabled(s.attack_state == EventsModel::Status::OFFENSE && has_selection_with_player);
477         ui->goal->setEnabled(s.attack_state == EventsModel::Status::OFFENSE && has_selection_with_player);
478         ui->offensive_soft_plus->setEnabled(s.attack_state == EventsModel::Status::OFFENSE && has_selection_with_player);
479         ui->offensive_soft_minus->setEnabled(s.attack_state == EventsModel::Status::OFFENSE && has_selection_with_player);
480         ui->pull->setEnabled(false);
481
482         ui->interception->setEnabled(s.attack_state == EventsModel::Status::DEFENSE && has_selection_with_player);
483         ui->their_throwaway->setEnabled(s.attack_state == EventsModel::Status::DEFENSE);
484         ui->our_defense->setEnabled(s.attack_state == EventsModel::Status::DEFENSE && has_selection_with_player);
485         ui->their_goal->setEnabled(s.attack_state == EventsModel::Status::DEFENSE);
486         ui->defensive_soft_plus->setEnabled(s.attack_state == EventsModel::Status::DEFENSE && has_selection_with_player);
487         ui->defensive_soft_minus->setEnabled(s.attack_state == EventsModel::Status::DEFENSE && has_selection_with_player);
488         ui->their_pull->setEnabled(false);
489 }
490
491 void MainWindow::formation_double_clicked(bool offense, unsigned row)
492 {
493         FormationsModel *formations = offense ? offensive_formations : defensive_formations;
494         int id = formations->get_formation_id(row);
495         if (id == -1) {  // “Add new” clicked.
496                 bool ok;
497                 QString new_formation_str = QInputDialog::getText(this, "New formation", "Choose name for new formation:", QLineEdit::Normal, "", &ok);
498                 if (!ok || new_formation_str.isEmpty()) {
499                         return;
500                 }
501
502                 id = formations->insert_new(new_formation_str.toStdString());
503                 QListView *view = offense ? ui->offensive_formation_view : ui->defensive_formation_view;
504                 view->selectionModel()->select(formations->index(formations->get_row_from_id(id), 0), QItemSelectionModel::ClearAndSelect);
505                 events->inserted_new_formation(id, new_formation_str.toStdString());
506         } else {
507                 events->set_formation_at(video->position(), offense, id);
508         }
509 }
510
511 sqlite3 *open_db(const char *filename)
512 {
513         sqlite3 *db;
514         int ret = sqlite3_open(filename, &db);
515         if (ret != SQLITE_OK) {
516                 fprintf(stderr, "%s: %s\n", filename, sqlite3_errmsg(db));
517                 exit(1);
518         }
519
520         sqlite3_exec(db, R"(
521                 CREATE TABLE IF NOT EXISTS player (player INTEGER PRIMARY KEY, number VARCHAR, name VARCHAR, gender VARCHAR(1));
522         )", nullptr, nullptr, nullptr);  // Ignore errors.
523
524         sqlite3_exec(db, R"(
525                 CREATE TABLE IF NOT EXISTS match (match INTEGER PRIMARY KEY, description VARCHAR);
526         )", nullptr, nullptr, nullptr);  // Ignore errors.
527
528         sqlite3_exec(db, R"(
529                 CREATE TABLE IF NOT EXISTS formation (formation INTEGER PRIMARY KEY, name VARCHAR, offense BOOLEAN NOT NULL);
530         )", nullptr, nullptr, nullptr);  // Ignore errors.
531
532         sqlite3_exec(db, R"(
533                 CREATE TABLE IF NOT EXISTS event (event INTEGER PRIMARY KEY, match INTEGER, t INTEGER, player INTEGER, type VARCHAR, formation INTEGER, FOREIGN KEY (player) REFERENCES player(player), FOREIGN KEY (match) REFERENCES match (match), FOREIGN KEY (formation) REFERENCES formation (formation));
534         )", nullptr, nullptr, nullptr);  // Ignore errors.
535
536         sqlite3_exec(db, "PRAGMA journal_mode=WAL", nullptr, nullptr, nullptr);  // Ignore errors.
537         sqlite3_exec(db, "PRAGMA synchronous=NORMAL", nullptr, nullptr, nullptr);  // Ignore errors.
538         sqlite3_exec(db, "PRAGMA foreign_keys=ON", nullptr, nullptr, nullptr);  // Ignore errors.
539         return db;
540 }
541
542 int get_match_id(sqlite3 *db, QWidget *parent, int requested_match)
543 {
544         QStringList items;
545         vector<int> ids;
546         bool requested_match_ok = false;
547
548         // Read the list of matches already in the database.
549         sqlite3_stmt *stmt;
550         int ret = sqlite3_prepare_v2(db, "SELECT match, description FROM match ORDER BY match", -1, &stmt, 0);
551         if (ret != SQLITE_OK) {
552                 fprintf(stderr, "SELECT prepare: %s\n", sqlite3_errmsg(db));
553                 abort();
554         }
555         for ( ;; ) {
556                 ret = sqlite3_step(stmt);
557                 if (ret == SQLITE_ROW) {
558                         char buf[256];
559                         snprintf(buf, sizeof(buf), "%s (%d)", sqlite3_column_text(stmt, 1), sqlite3_column_int(stmt, 0));
560                         ids.push_back(sqlite3_column_int(stmt, 0));
561                         if (ids.back() == requested_match) {
562                                 requested_match_ok = true;
563                         }
564                         items.push_back(buf);
565                 } else if (ret == SQLITE_DONE) {
566                         break;
567                 } else {
568                         fprintf(stderr, "SELECT step: %s\n", sqlite3_errmsg(db));
569                         abort();
570                 }
571         }
572         ret = sqlite3_finalize(stmt);
573         if (ret != SQLITE_OK) {
574                 fprintf(stderr, "SELECT finalize: %s\n", sqlite3_errmsg(db));
575                 abort();
576         }
577         items.push_back("Add new…");
578
579         if (requested_match_ok) {
580                 return requested_match;
581         }
582
583         QString chosen_str;
584         {
585                 QInputDialog dialog(parent, Qt::WindowFlags());
586                 dialog.setWindowTitle("Open game");
587                 dialog.setLabelText("Choose game to analyze:");
588                 dialog.setComboBoxItems(items);
589                 dialog.setTextValue(items[items.size() - 2]);
590                 dialog.setOption(QInputDialog::UseListViewForComboBoxItems, true);
591                 if (!dialog.exec()) {
592                         return -1;
593                 }
594                 chosen_str = dialog.textValue();
595         }
596
597         for (unsigned i = 0; i < ids.size(); ++i) {
598                 if (chosen_str == items[i]) {
599                         return ids[i];
600                 }
601         }
602
603         // Must be a new game. Get its name and insert it into the database.
604         bool ok;
605         QString new_game_str = QInputDialog::getText(parent, "New game", "Choose name for new game:", QLineEdit::Normal, "", &ok);
606         if (!ok || new_game_str.isEmpty()) {
607                 return -1;
608         }
609
610         // Insert the new row into the database.
611         ret = sqlite3_prepare_v2(db, "INSERT INTO match (description) VALUES (?)", -1, &stmt, 0);
612         if (ret != SQLITE_OK) {
613                 fprintf(stderr, "INSERT prepare: %s\n", sqlite3_errmsg(db));
614                 abort();
615         }
616
617         QByteArray new_game_utf8 = new_game_str.toUtf8();
618         sqlite3_bind_text(stmt, 1, (const char *)new_game_utf8.data(), new_game_utf8.size(), SQLITE_STATIC);
619
620         ret = sqlite3_step(stmt);
621         if (ret == SQLITE_ROW) {
622                 fprintf(stderr, "INSERT step: %s\n", sqlite3_errmsg(db));
623                 abort();
624         }
625
626         ret = sqlite3_finalize(stmt);
627         if (ret != SQLITE_OK) {
628                 fprintf(stderr, "INSERT finalize: %s\n", sqlite3_errmsg(db));
629                 abort();
630         }
631
632         return sqlite3_last_insert_rowid(db);
633 }
634
635 int main(int argc, char *argv[])
636 {
637         QApplication app(argc, argv);
638         sqlite3 *db = open_db("ultimate.db");
639
640         // TODO: do this on-demand instead, from a menu
641         export_to_json(db, "ultimate.json");
642
643         int requested_match = -1;
644         if (argc >= 2) {
645                 requested_match = atoi(argv[1]);
646         }
647
648         int match_id = get_match_id(db, nullptr, requested_match);
649         if (match_id <= 0) {  // Cancel.
650                 return 0;
651         }
652
653         MainWindow mainWindow(new EventsModel(db, match_id), new PlayersModel(db),
654                               new FormationsModel(db, true), new FormationsModel(db, false));
655         mainWindow.resize(QSize(1280, 720));
656         mainWindow.show();
657
658         return app.exec();
659
660 }