+#include <cstdio>
+#include <algorithm>
+
+#include "top5chosenscreen.h"
+#include "fonts.h"
+
+Top5ChosenScreen::Top5ChosenScreen(pqxx::connection &conn, unsigned tournament)
+ : conn(conn), tournament(tournament), scores_changed(conn, "scores"), valid(false)
+{
+}
+
+Top5ChosenScreen::~Top5ChosenScreen()
+{
+}
+
+bool Top5ChosenScreen::check_invalidated()
+{
+ if (!valid)
+ return true;
+ if (!scores_changed.get_flag())
+ return false;
+
+ return true;
+}
+
+void Top5ChosenScreen::draw(unsigned char *buf)
+{
+ scores_changed.reset_flag();
+ memset(buf, 0, 800 * 600 * 4);
+
+ // fetch the top 5 chosen songs
+ std::vector<TopChosen> scores;
+ conn.perform(FetchTopChosenSongsForTournament(tournament, 5, &scores));
+
+ {
+ unsigned width = my_draw_text("Today's top 5 chosen songs", NULL, 40.0);
+ my_draw_text("Today's top 5 chosen songs", buf, 40.0, 800/2 - width/2, 60);
+ }
+
+ // simple headings
+ my_draw_text("Song", buf, 12.0, 70, 100);
+ my_draw_text("Frequency", buf, 12.0, 710, 100);
+
+ unsigned row = 1, y = 140;
+ for (std::vector<TopChosen>::const_iterator i = scores.begin(); i != scores.end(); ++i) {
+ char str[16];
+ unsigned r = 255, g = 255, b = 255;
+
+ // print new entries in red
+ if (seen_topchosen.count(*i) == 0 && seen_topchosen.size() > 0) {
+ g = b = 0;
+ }
+
+ std::sprintf(str, "%u", row++);
+ unsigned width = my_draw_text(str, NULL, 24.0);
+ my_draw_text(str, buf, 24.0, 30 - width/2, y);
+
+ if (my_draw_text(i->title, NULL, 24.0) > 610) {
+ my_draw_text(i->shorttitle, buf, 24.0, 70, y, r, g, b);
+ } else {
+ my_draw_text(i->title, buf, 24.0, 70, y, r, g, b);
+ }
+
+ std::sprintf(str, "%u", i->frequency);
+ width = my_draw_text(str, NULL, 24.0);
+ my_draw_text(str, buf, 24.0, 728 - width/2, y, r, g, b);
+
+ y += 40;
+ }
+
+ valid = true;
+
+ seen_topchosen.erase(seen_topchosen.begin(), seen_topchosen.end());
+ std::copy(scores.begin(), scores.end(), std::inserter(seen_topchosen, seen_topchosen.end()));
+}
+