#!/usr/bin/env python3

import sqlite3
import json
from http.server import HTTPServer, BaseHTTPRequestHandler

CONFIGNAME="supertuxkart"
DATABASEFILE='/etc/supertuxkart/stkservers.db'

def results_as_json():
    cx = sqlite3.connect(DATABASEFILE)
    grandprixes = []
    grandprix_cursor = cx.cursor()
    for grandprix_row in grandprix_cursor.execute(f'SELECT ROWID, num_races, total_races FROM v1_{CONFIGNAME}_grandprixresults'):
        races = []
        race_cursor = cx.cursor()
        for race_row in race_cursor.execute(f'SELECT ROWID, track_name FROM v1_{CONFIGNAME}_raceresults WHERE grandprix_rowid = {grandprix_row[0]}'):
            race = {"track": race_row[1], "players": []}
            player_cursor = cx.cursor()
            for player_row in player_cursor.execute(f'SELECT elapsed_time, player_name FROM v1_your_config_playerresults WHERE race_rowid = {race_row[0]} ORDER BY elapsed_time ASC'):
                race['players'].append({"name": player_row[1], "time": player_row[0]})
            races.append(race)
        grandprixes.append({"num_races": grandprix_row[1], "total_races": grandprix_row[2], "races": races})
    cx.close()

    return json.dumps(grandprixes, indent=None, separators=(',', ':'))

class STKStatServer(BaseHTTPRequestHandler):
    def do_GET(self):
        self.send_response(200)
        self.send_header("Content-Type", "application/json")
        self.send_header("Access-Control-Allow-Origin", "*")
        self.end_headers()

        self.wfile.write(results_as_json().encode('utf-8'))

if __name__ == "__main__":
    server = HTTPServer(("127.0.0.1", 9985), STKStatServer)
    server.serve_forever()
