-
Notifications
You must be signed in to change notification settings - Fork 78
Expand file tree
/
Copy pathfuelDatabase.ts
More file actions
100 lines (85 loc) · 2.57 KB
/
Copy pathfuelDatabase.ts
File metadata and controls
100 lines (85 loc) · 2.57 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
import { app } from 'electron';
import path from 'node:path';
import fs from 'node:fs';
import type { FuelLapData } from '../../types';
import logger from '../logger';
interface FuelStorageFormat {
laps: Record<string, FuelLapData[]>;
settings: Record<string, { qualifyMax: number | null }>;
}
export class FuelDatabase {
private filePath: string;
private data: FuelStorageFormat;
constructor() {
const dataPath = app.getPath('userData');
this.filePath = path.join(dataPath, 'fuel_data.json');
this.data = this.load();
}
private load(): FuelStorageFormat {
try {
if (fs.existsSync(this.filePath)) {
const content = fs.readFileSync(this.filePath, 'utf-8');
return JSON.parse(content);
}
} catch (e) {
logger.error('[FuelDatabase] Failed to load data:', e);
}
return { laps: {}, settings: {} };
}
private save() {
try {
fs.writeFileSync(
this.filePath,
JSON.stringify(this.data, null, 2),
'utf-8'
);
} catch (e) {
logger.error('[FuelDatabase] Failed to save data:', e);
}
}
private getContextKey(trackId: string | number, carName: string): string {
return `${trackId}:${carName}`;
}
public saveLap(trackId: string | number, carName: string, lap: FuelLapData) {
const key = this.getContextKey(trackId, carName);
if (!this.data.laps[key]) {
this.data.laps[key] = [];
}
// Add new lap (at the beginning for easier retrieval of 10 most recent)
this.data.laps[key].unshift({ ...lap, isHistorical: true });
// Prune to keep only 10 most recent
if (this.data.laps[key].length > 10) {
this.data.laps[key] = this.data.laps[key].slice(0, 10);
}
this.save();
}
public getLaps(trackId: string | number, carName: string): FuelLapData[] {
const key = this.getContextKey(trackId, carName);
return this.data.laps[key] || [];
}
public saveQualifyMax(
trackId: string | number,
carName: string,
val: number | null
) {
const key = this.getContextKey(trackId, carName);
this.data.settings[key] = { qualifyMax: val };
this.save();
}
public getQualifyMax(
trackId: string | number,
carName: string
): number | null {
const key = this.getContextKey(trackId, carName);
return this.data.settings[key]?.qualifyMax ?? null;
}
public clearLaps(trackId: string | number, carName: string) {
const key = this.getContextKey(trackId, carName);
this.data.laps[key] = [];
this.save();
}
public clearAllLaps() {
this.data = { laps: {}, settings: {} };
this.save();
}
}