tg-bot-ts/src/systems/history.ts

88 lines
2.5 KiB
TypeScript

import fs from "fs";
import path from "path";
import { TGResult, TGScore, Nation } from "../types";
import { Nations } from "@systems/nations";
import { Store } from "@systems/store";
import { Paths } from "@helpers/paths";
const HISTORY_DIR = path.join(__dirname, "../../data/tg-history");
function historyKey(date: string, slot: number): string {
return `${date}-${String(slot).padStart(2, "0")}`;
}
function historyPath(key: string): string {
return path.join(HISTORY_DIR, `${key}.json`);
}
export function loadResult(date: string, slot: number): TGResult | null {
return Store.read(historyPath(historyKey(date, slot)));
}
export function saveResult(result: TGResult): void {
if (!fs.existsSync(HISTORY_DIR)) fs.mkdirSync(HISTORY_DIR, { recursive: true });
Store.write(historyPath(historyKey(result.date, result.slot)), result);
}
export function upsertScore(score: TGScore): void {
const result = loadResult(score.date, score.slot) ?? {
slot: score.slot,
date: score.date,
confirmed: false,
nationKD: {
source: Nation.Procyon,
capella: { k: 0, d: 0 },
procyon: { k: 0, d: 0 },
},
scores: [],
};
// Overwrite existing score for this player+slot
result.scores = result.scores.filter(
(s) => !(s.userKey === score.userKey && s.characterName === score.characterName && s.slot === score.slot && s.date === score.date)
);
result.scores.push(score);
saveResult(result);
}
export function setNationKD(
date: string,
slot: number,
sourceNation: Nation,
k: number,
d: number
): TGResult {
const result = loadResult(date, slot) ?? {
slot,
date,
confirmed: false,
nationKD: { source: sourceNation, capella: { k: 0, d: 0 }, procyon: { k: 0, d: 0 } },
scores: [],
};
result.nationKD.source = sourceNation;
const other = Nations.opposite(sourceNation);
result.nationKD[sourceNation.toLowerCase() as "capella" | "procyon"] = { k, d };
result.nationKD[other.toLowerCase() as "capella" | "procyon"] = { k: d, d: k };
saveResult(result);
return result;
}
export function listRecentResults(limit = 10): TGResult[] {
if (!fs.existsSync(HISTORY_DIR)) return [];
return fs.readdirSync(HISTORY_DIR)
.filter((f) => f.endsWith(".json"))
.sort()
.reverse()
.slice(0, limit)
.map((f) => {
try { return JSON.parse(fs.readFileSync(path.join(HISTORY_DIR, f), "utf8")) as TGResult; }
catch { return null; }
})
.filter(Boolean) as TGResult[];
}
export function todayString(): string {
return new Date().toISOString().slice(0, 10);
}