244 lines
16 KiB
C++
244 lines
16 KiB
C++
// SPDX-License-Identifier: GPL-3.0-only
|
|
#include "modern/ui/demo_statistics.hpp"
|
|
#include "modern/ui/demo_career.hpp"
|
|
#include <algorithm>
|
|
#include <array>
|
|
#include <chrono>
|
|
#include <cmath>
|
|
#include <optional>
|
|
#include <set>
|
|
|
|
namespace bmh::modern_ui {
|
|
namespace {
|
|
const std::array<const char *,9> sections{"Möglichkeiten","Transferhistorie","Analytics","Ewige Tabelle","WM-Statistiken","Saisonfinanzen","Serien u. Rekorde","Sieger","Minuten-Statistik"};
|
|
const std::array<const char *,6> views{"Sieger","Gruppen","Torschützen","Finalrunde","Tabelle","Historie"};
|
|
const std::array<const char *,6> curves{"Kontostand","Mannschaftsstärke","Zuschauer","Stimmung","Einnahmen","Ausgaben"};
|
|
const std::array<const char *,6> colors{"#e3da6a","#79b5c8","#a9d67b","#e58a66","#ded9bd","#b295cd"};
|
|
const std::array<std::array<int,3>,12> domestic{{{{0,0,1}},{{1,3,1}},{{3,1,3}},{{2,4,1}},{{1,1,4}},{{0,2,0}},{{3,3,1}},{{1,5,1}},{{2,1,2}},{{1,1,0}},{{3,0,3}},{{4,2,1}}}};
|
|
const Json &field(const Json &value,const char *key) {
|
|
static const Json missing;
|
|
if(value.is_object())if(const auto i=value.find(key);i!=value.end())return *i;
|
|
return missing;
|
|
}
|
|
std::string string(const Json &value,const std::string &fallback="") {
|
|
return value.is_string()?value.get<std::string>():fallback;
|
|
}
|
|
std::optional<int> season_year(const Json &value) {
|
|
if(!value.is_string())return {};
|
|
const auto d=value.get<std::string>();
|
|
if(d.size()!=10||d[4]!='-'||d[7]!='-')return {};
|
|
for(size_t i=0;i<d.size();++i)if(i!=4&&i!=7&&(d[i]<'0'||d[i]>'9'))return {};
|
|
const int y=std::stoi(d.substr(0,4)),m=std::stoi(d.substr(5,2)),day=std::stoi(d.substr(8,2));
|
|
if(!std::chrono::year_month_day{std::chrono::year{y},std::chrono::month{unsigned(m)},std::chrono::day{unsigned(day)}}.ok())return {};
|
|
return y-(m<7?1:0);
|
|
}
|
|
std::string season(int year) {
|
|
auto end=std::to_string((year+1)%100);
|
|
return std::to_string(year)+"/"+(end.size()<2?"0":"")+end;
|
|
}
|
|
Json cell(const std::string &text) {return {{"text",text}};}
|
|
Json numeric(int value) {return {{"text",std::to_string(value)},{"value",value}};}
|
|
Json club_cell(const Catalog &world,const Json *club) {
|
|
if(!club)return cell("—");
|
|
return {{"text",world.name(*club)},{"club",club->at("id")}};
|
|
}
|
|
Json nation_cell(const Catalog &world,const Json *nation) {
|
|
return nation?Json{{"text",world.name(*nation)},{"nation",nation->at("id")}}:cell("—");
|
|
}
|
|
Json player_cell(const Catalog &world,const Json *player) {
|
|
return player?Json{{"text",world.name(*player)},{"player",player->at("id")},{"club",player->value("team","")}}:cell("—");
|
|
}
|
|
void headings(Json &out,std::initializer_list<const char *> names) {
|
|
for(const auto *name:names)out["columns"].push_back({{"text",name}});
|
|
}
|
|
void row(Json &out,Json cells) {out["rows"].push_back({{"cells",std::move(cells)}});}
|
|
const Json *country_nation(const Catalog &world, const std::string &code) {
|
|
if (const auto *nation = world.find("nations", "nation:" + code))
|
|
return nation;
|
|
// England has no ISO alpha-2 country of its own. OBW retains the stable
|
|
// imported football-nation identity instead of replacing it with the UK.
|
|
if (code == "en")
|
|
for (const auto *id : {"nation:x-eng", "nation:eng"})
|
|
if (const auto *nation = world.find("nations", id)) return nation;
|
|
return nullptr;
|
|
}
|
|
std::string statistics_country_code(const Json *nation) {
|
|
if (!nation) return {};
|
|
const auto id = nation->value("id", "");
|
|
const auto code = id.starts_with("nation:") ? id.substr(7) : id;
|
|
return code == "x-eng" || code == "eng" ? "en" : code;
|
|
}
|
|
std::vector<const Json *> countries(const Catalog &world) {
|
|
std::vector<const Json *> result;
|
|
std::set<std::string> seen;
|
|
// Match Gold's fixed domestic ordering; retain actual IDs and captions.
|
|
for(const auto *code:{"de","es","it","fr","en"})
|
|
if(const auto *nation=country_nation(world,code);nation&&!world.leagues(nation->at("id").get<std::string>()).empty()) {
|
|
result.push_back(nation);seen.insert(nation->at("id").get<std::string>());
|
|
}
|
|
for(const auto *league:world.leagues()) {
|
|
const auto id=league->value("nation","");
|
|
if(const auto *nation=world.find("nations",id);nation&&seen.insert(id).second)result.push_back(nation);
|
|
}
|
|
return result;
|
|
}
|
|
std::vector<const Json *> first_league_clubs(const Catalog &world,const Json *nation) {
|
|
if(!nation)return {};
|
|
const auto leagues=world.leagues(nation->at("id").get<std::string>());
|
|
if(leagues.empty())return {};
|
|
// Catalog order is canonical; lower-tier competitions are never mixed in.
|
|
const Json *first=leagues.front();
|
|
for(const auto *league:leagues)if(league->value("tier",1)<first->value("tier",1))first=league;
|
|
return world.clubs(first->at("id").get<std::string>());
|
|
}
|
|
const Json *at(const std::vector<const Json *> &items,size_t index) {
|
|
return items.empty()?nullptr:items[index%items.size()];
|
|
}
|
|
} // namespace
|
|
|
|
Json demo_statistics(const Catalog &world,const Json &state,const Json &request) {
|
|
const auto reject=[](const std::string &error){return Json{{"ok",false},{"fictional",true},{"error",error}};};
|
|
if(!request.is_object())return reject("invalid_statistics_request");
|
|
for(const auto &[key,value]:request.items())if(key!="section"&&key!="category"&&key!="country"&&key!="winner_country"&&key!="absolute"&&key!="curves")return reject("unknown_statistics_filter");
|
|
const auto integer=[&](const char *key,int fallback,int maximum)->std::optional<int>{
|
|
if(!request.contains(key))return fallback;
|
|
const auto &v=request.at(key);
|
|
if(!v.is_number_integer()||v<0||v>maximum)return {};
|
|
return v.get<int>();
|
|
};
|
|
const auto section=integer("section",7,8),category=integer("category",0,5),country=integer("country",0,5);
|
|
if(!section||!category||!country||(*category!=0&&*category!=1&&*category!=5))return reject("invalid_statistics_filter");
|
|
if(request.contains("absolute")&&!request.at("absolute").is_boolean())return reject("invalid_statistics_absolute");
|
|
Json active=Json::array({true,true,true,true,true,true});
|
|
if(request.contains("curves")) {
|
|
const auto &value=request.at("curves");
|
|
if(!value.is_array()||value.size()!=6||!std::all_of(value.begin(),value.end(),[](const Json &v){return v.is_boolean();}))return reject("invalid_statistics_curves");
|
|
active=value;
|
|
}
|
|
const auto nations=countries(world);
|
|
const auto winner=request.contains("winner_country")?string(request.at("winner_country")):nations.empty()?"":nations.front()->at("id").get<std::string>();
|
|
if(request.contains("winner_country")&&(!request.at("winner_country").is_string()||std::none_of(nations.begin(),nations.end(),[&](const Json *n){return n->at("id")==winner;})))return reject("invalid_statistics_country");
|
|
const Json *own=nullptr;std::string manager_name="—";
|
|
const auto &managers=field(state,"managers");
|
|
if(managers.is_array()&&!managers.empty()) {
|
|
own=world.find("clubs",string(field(demo_career_manager(state),"club")));
|
|
if(own&&(own->value("type","club")!="club"||state.value("career",Json::object()).value("role","club")=="national"))own=nullptr;
|
|
const auto name=string(field(demo_career_manager(state),"name"));if(!name.empty())manager_name=name;
|
|
}
|
|
int year=season_year(field(state,"date")).value_or(season_year(world.manifest().value("start_date",Json())).value_or(2027));
|
|
const bool absolute=request.value("absolute",false);
|
|
Json out={{"ok",true},{"fictional",true},{"available",true},{"section",*section},{"category",*category},{"country",*country},{"winner_country",winner},{"absolute",absolute},{"curves",active},{"title",sections[size_t(*section)]},{"season",season(year)},{"previous_season",season(year-1)},{"year",year},{"manager",manager_name},{"club",own?own->at("id"):Json()},{"columns",Json::array()},{"rows",Json::array()},{"countries",Json::array()},{"sections",sections},{"world_views",views},{"series",Json::array()}};
|
|
for(const auto *n:nations)out["countries"].push_back({{"id",n->at("id")},{"name",world.name(*n)}});
|
|
out["eternal_countries"] = Json::array();
|
|
const std::array<const char *, 5> eternal_codes{"de", "es", "en", "fr", "it"};
|
|
for (size_t i = 0; i < eternal_codes.size(); ++i)
|
|
if (const auto *n = country_nation(world, eternal_codes[i]))
|
|
out["eternal_countries"].push_back({{"value", i}, {"nation", n->at("id")}, {"name", world.name(*n)}});
|
|
out["eternal_countries"].push_back({{"value", 5}, {"name", "Absolut"}});
|
|
auto own_league=own?world.clubs(own->value("competition","")):std::vector<const Json *>{};
|
|
if(own&&own_league.empty())own_league.push_back(own);
|
|
if(!own&& !nations.empty())own_league=first_league_clubs(world,nations.front());
|
|
// Gold uses one German/own-league cohort for possibilities and records.
|
|
const auto clubs=own_league;
|
|
const auto players=own?world.squad(own->at("id").get<std::string>()):std::vector<const Json *>{};
|
|
if(*section==0) {
|
|
headings(out,{"Verein","Meisterschaft","Pokal","Europapokal"});
|
|
for(size_t i=0;i<std::min(size_t(14),clubs.size());++i)row(out,Json::array({club_cell(world,clubs[i]),cell(std::to_string(std::max(0,72-int(i)*5))+" %"),cell(std::to_string(std::max(0,35-int(i)*2))+" %"),cell(std::to_string(std::max(0,22-int(i)))+" %")}));
|
|
} else if(*section==1) {
|
|
headings(out,{"Saison / Spieler","Von","Nach","Ablöse"});
|
|
for(size_t i=0;i<std::min(size_t(10),players.size());++i) {
|
|
auto p=player_cell(world,players[i]);p["prefix"]=std::to_string(year-int(i%3))+" · ";
|
|
row(out,Json::array({p,club_cell(world,at(clubs,i+1)),club_cell(world,own),{{"text",number(450000+int(i)*215000)+" €"},{"value",450000+int(i)*215000}}}));
|
|
}
|
|
} else if(*section==2) {
|
|
for(size_t k=0;!clubs.empty()&&k<6;++k) {
|
|
Json points=Json::array();
|
|
for(int i=0;i<24;++i)points.push_back({50+i*140,absolute?700-(i*7+int(k)*22):650-(200+std::sin(i*.45+double(k))*145+i*6)});
|
|
out["series"].push_back({{"name",curves[k]},{"color",colors[k]},{"active",active[k]},{"points",points}});
|
|
}
|
|
} else if(*section==3) {
|
|
headings(out,{"Verein","Sp.","S","U","N","Punkte","Tore"});
|
|
const auto selected=*country==5?clubs:first_league_clubs(world,country_nation(world,eternal_codes[size_t(*country)]));
|
|
for(size_t i=0;i<selected.size();++i)row(out,Json::array({club_cell(world,selected[i]),numeric(158-int(i)*3-*country*4),numeric(91-int(i)*3),numeric(31+int(i%5)),numeric(36+int(i%7)),numeric(304-int(i)*12-*country*3),cell(std::to_string(219-int(i)*5)+":"+std::to_string(146+int(i)*4))}));
|
|
} else if(*section==4) {
|
|
std::vector<const Json *> ns;
|
|
for(const auto *code:{"de","es","fr","it","en","nl","pt","be"})if(const auto *n=country_nation(world,code))ns.push_back(n);
|
|
for(const auto &n:world.rows("nations"))if(ns.size()<8&&std::find(ns.begin(),ns.end(),&n)==ns.end())ns.push_back(&n);
|
|
if(*country==0||*country==5) {
|
|
headings(out,{"WM / EM","Sieger","Finalist","Finale"});
|
|
for(size_t i=0;i<std::min(size_t(6),ns.size());++i) {
|
|
auto tournament=cell(std::string(i%2?"EM ":"WM ")+std::to_string(year-1-int(i)*2));
|
|
tournament["trophy"]=i%2?"european-championship":"world-cup";tournament["winner"]=ns[i]->at("id");tournament["season"]=std::to_string(year-1-int(i)*2);
|
|
row(out,Json::array({tournament,nation_cell(world,ns[i]),nation_cell(world,at(ns,i+1)),cell(std::to_string(i%3+1)+":"+std::to_string(i%2))}));
|
|
}
|
|
} else if(*country==1) {
|
|
headings(out,{"Gruppe","Mannschaft","Spiele","Punkte"});
|
|
for(size_t i=0;i<ns.size();++i)row(out,Json::array({cell(std::string("Gruppe ")+char('A'+i/4)),nation_cell(world,ns[i]),numeric(3),numeric(9-int(i%4)*2)}));
|
|
} else if(*country==2) {
|
|
headings(out,{"Spieler","Land","Tore"});
|
|
for(size_t i=0;i<std::min({size_t(8),players.size(),ns.size()});++i)row(out,Json::array({player_cell(world,players[i]),nation_cell(world,ns[i]),numeric(8-int(i))}));
|
|
} else if(*country==3) {
|
|
headings(out,{"Heim","Ergebnis","Auswärts"});out["columns"][0]["round"]="Runde";
|
|
const std::array<const char *,4> rounds{"Finale","Halbfinale","Halbfinale","Viertelfinale"};
|
|
for(size_t i=0;i<std::min(size_t(4),ns.size());++i) {
|
|
auto home=nation_cell(world,ns[i]);home["round"]=rounds[i];
|
|
row(out,Json::array({home,cell(std::to_string(i%3+1)+":"+std::to_string(i%2)),nation_cell(world,ns[ns.size()-1-i])}));
|
|
}
|
|
} else {
|
|
headings(out,{"Land","Spiele","Siege","Punkte"});
|
|
for(size_t i=0;i<ns.size();++i)row(out,Json::array({nation_cell(world,ns[i]),numeric(20-int(i)),numeric(15-int(i)),numeric(45-int(i)*3)}));
|
|
}
|
|
} else if(*section==5) {
|
|
headings(out,{"Saison","Einnahmen","Ausgaben","Saldo"});
|
|
if(own)for(int i=0;i<10;++i)row(out,Json::array({numeric(year-i),cell(number(14500000-i*125000)+" €"),cell(number(13800000-i*85000)+" €"),cell(number(700000-i*40000)+" €")}));
|
|
} else if(*section==6) {
|
|
headings(out,{"Serie / Rekord","Verein","Wert"});
|
|
const std::array<const char *,8> names{"Ungeschlagen","Siege in Folge","Heimsiege","Auswärtssiege","Tore in einer Saison","Höchster Sieg","Längste Torserie","Meiste Zuschauer"};
|
|
for(size_t i=0;i<std::min(size_t(8),clubs.size());++i)row(out,Json::array({cell(names[i]),club_cell(world,clubs[i]),cell(i<4?std::to_string(22-int(i)):i==5?"7 : 0":i==7?"48.500":std::to_string(75-int(i)))}));
|
|
} else if(*section==7) {
|
|
const auto *nation=world.find("nations",winner);const auto domestic_clubs=first_league_clubs(world,nation);
|
|
const auto code=statistics_country_code(nation);
|
|
std::vector<std::string> titles,trophies;
|
|
if(*category==0) {
|
|
if(code=="es"){titles={"Primera División","Copa del Rey","Supercopa"};trophies={"es-la-liga","es-copa-del-rey",""};}
|
|
else if(code=="en"){titles={"Premier League","FA Cup","League Cup"};trophies={"en-premier-league","en-fa-cup",""};}
|
|
else if(code=="fr"){titles={"Ligue 1","Coupe de France","Trophée des Champions"};trophies={"fr-ligue-1","fr-coupe-de-france",""};}
|
|
else if(code=="it"){titles={"Serie A","Coppa Italia","Supercoppa"};trophies={"it-serie-a","it-coppa-italia",""};}
|
|
else {titles={"Meisterschaft","DFB-Pokal","Supercup"};trophies={"championship","dfb-cup","supercup"};}
|
|
out["note"]=(nation?world.name(*nation):"—")+" · Titelträger im Saisonvergleich";
|
|
} else if(*category==1){titles={"Champions League","Pokalsieger","UEFA-Cup"};trophies={"champions-league","cup-winners","uefa-cup"};out["note"]="Europäische Titelträger im Saisonvergleich";}
|
|
else {titles={"Sieger","Finalist"};trophies={"indoor-masters",""};out["note"]="Hallenmasters · Sieger und Finalisten";}
|
|
headings(out,{"Saison"});
|
|
std::vector<const Json *> international;
|
|
const std::array<const char *,12> preferred{"club:es-real-madrid","club:en-manchester-city","club:it-ac-mailand","club:es-fc-barcelona","club:en-liverpool","club:de-bayern-muenchen","club:fr-paris-saint-germain","club:it-inter-mailand","club:de-borussia-dortmund","club:en-chelsea","club:it-juventus-turin","club:es-fc-sevilla"};
|
|
for(const auto *id:preferred)if(const auto *club=world.find("clubs",id))international.push_back(club);
|
|
if(international.empty())for(size_t i=0;i<12;++i) {
|
|
if(nations.empty())break;
|
|
const auto candidates=first_league_clubs(world,nations[i%nations.size()]);
|
|
if(const auto *club=at(candidates,i/nations.size()))if(std::find(international.begin(),international.end(),club)==international.end())international.push_back(club);
|
|
}
|
|
for(size_t col=0;col<titles.size();++col)out["columns"].push_back({{"text",titles[col]},{"trophy",trophies[col]}});
|
|
const bool available=*category==0?!domestic_clubs.empty():*category==1?!international.empty():!clubs.empty();
|
|
if(available)for(size_t i=0;i<12;++i) {
|
|
Json cells=Json::array({cell(season(year-1-int(i)))});
|
|
for(size_t col=0;col<titles.size();++col) {
|
|
const auto *club=*category==0?at(domestic_clubs,size_t(domestic[i][col])):*category==1?at(international,i+col*4):at(clubs,i*3+(col?7:2));
|
|
cells.push_back(club_cell(world,club));
|
|
if(i==0)out["columns"][col+1]["winner"]=club?club->at("id"):Json();
|
|
}
|
|
row(out,std::move(cells));
|
|
}
|
|
} else {
|
|
headings(out,{"Ereignis"});for(int i=0;i<18;++i)out["columns"].push_back(cell(std::to_string(i*5)+"."));
|
|
const std::array<const char *,4> names{"Tore","Chancen","Gelb","Rot"};
|
|
if(own)for(int k=0;k<4;++k) {
|
|
Json cells=Json::array({cell(names[size_t(k)])});
|
|
for(int i=0;i<18;++i){auto c=numeric((i*3+k)%13);c["tone"]=(i+k)%5==0?"bad":(i+k)%3==0?"good":"";cells.push_back(c);}
|
|
row(out,std::move(cells));
|
|
}
|
|
}
|
|
out["available"]=*section==2?!clubs.empty():!out["rows"].empty();
|
|
return out;
|
|
}
|
|
} // namespace bmh::modern_ui
|