Files
SDKmuta/lib/services/target_repository.dart
T
2026-10-26 20:48:16 +01:00

218 lines
7.2 KiB
Dart

import 'dart:convert';
import 'dart:io';
import 'package:path_provider/path_provider.dart';
/// One saved target (a JSON file written by the preview screen).
class TargetRecord {
final File file;
final DateTime shotAt;
final int score;
final int shots;
const TargetRecord(
{required this.file,
required this.shotAt,
required this.score,
required this.shots});
}
/// A folder of targets: one training or tournament.
class Session {
final String name;
final bool isTournament;
final DateTime date;
final List<TargetRecord> targets; // oldest first
const Session(
{required this.name,
required this.isTournament,
required this.date,
required this.targets});
int get totalScore => targets.fold(0, (sum, t) => sum + t.score);
int get shots => targets.fold(0, (sum, t) => sum + t.shots);
double? get averagePerShot => shots == 0 ? null : totalScore / shots;
List<File> get files => [for (final t in targets) t.file];
/// The same session limited to targets with [shots] bullets (null = all).
Session onlyShots(int? shots) => shots == null
? this
: Session(name: name, isTournament: isTournament, date: date, targets: [
for (final t in targets)
if (t.shots == shots) t,
]);
}
/// Aggregates over any set of sessions (trainings or tournaments of one format).
class ShooterStats {
final int sessions;
final int targets;
final int shots;
final TargetRecord? best;
final double? averageTarget;
final double? averagePerShot;
const ShooterStats._({
required this.sessions,
required this.targets,
required this.shots,
required this.best,
required this.averageTarget,
required this.averagePerShot,
});
factory ShooterStats.of(List<Session> sessions) {
final all = [for (final s in sessions) ...s.targets];
final shots = all.fold(0, (sum, t) => sum + t.shots);
final total = all.fold(0, (sum, t) => sum + t.score);
final ranked = [...all]..sort((a, b) => b.score.compareTo(a.score));
final mean = all.isEmpty ? null : total / all.length;
return ShooterStats._(
sessions: sessions.length,
targets: all.length,
shots: shots,
best: ranked.isEmpty ? null : ranked.first,
averageTarget: mean,
averagePerShot: shots == 0 ? null : total / shots,
);
}
}
/// Reads and edits the saved targets under <documents>/saved_images/<session>/.
class TargetRepository {
static Future<Directory> _root() async {
final dir = Directory(
'${(await getApplicationDocumentsDirectory()).path}/saved_images');
if (!await dir.exists()) await dir.create(recursive: true);
return dir;
}
/// Sessions, newest first. With [year], only that year's target files are read.
static Future<List<Session>> loadSessions({int? year}) async {
final sessions = <Session>[];
for (final folder in await _folders()) {
if (year != null && folder.date.year != year) continue;
final targets = <TargetRecord>[];
for (final file in folder.targetFiles) {
final record = await _readTarget(file);
if (record != null) targets.add(record);
}
targets.sort((a, b) => a.shotAt.compareTo(b.shotAt));
sessions.add(Session(
name: folder.name,
isTournament: folder.isTournament,
date: folder.date,
targets: targets,
));
}
sessions.sort((a, b) => b.date.compareTo(a.date));
return sessions;
}
/// Years that have at least one session, newest first. Reads only metadata.
static Future<List<int>> years() async {
final years = {for (final f in await _folders()) f.date.year}.toList();
return years..sort((a, b) => b.compareTo(a));
}
// Cheap pass over the folders: metadata + file names, no target files read
static Future<List<_FolderInfo>> _folders() async {
final root = await _root();
final result = <_FolderInfo>[];
for (final folder in root.listSync().whereType<Directory>()) {
final meta = await _readMetadata(folder);
final files = [
for (final f in folder.listSync().whereType<File>())
if (f.path.endsWith('.json') && !f.path.endsWith('metadata.json')) f,
];
final fileTimes = files.map(_timeFromFileName).whereType<DateTime>().toList()..sort();
result.add(_FolderInfo(
name: folder.path.split('/').last,
isTournament: meta['isTournament'] == true,
date: DateTime.tryParse(meta['createdAt'] ?? '') ??
(fileTimes.isNotEmpty ? fileTimes.first : folder.statSync().changed),
targetFiles: files,
));
}
return result;
}
static Future<Map<String, dynamic>> _readMetadata(Directory folder) async {
final file = File('${folder.path}/metadata.json');
if (!await file.exists()) return {};
try {
return jsonDecode(await file.readAsString()) as Map<String, dynamic>;
} catch (_) {
return {};
}
}
static Future<TargetRecord?> _readTarget(File file) async {
try {
final data =
jsonDecode(await file.readAsString()) as Map<String, dynamic>;
final score = data['totalScore'];
return TargetRecord(
file: file,
shotAt: _timeFromFileName(file) ?? file.statSync().modified,
score: score is int ? score : 0,
// Older saves have no bulletCount: fall back to the detected bullets
shots: data['bulletCount'] as int? ??
(data['bullets'] as List?)?.length ??
0,
);
} catch (_) {
return null;
}
}
// File names look like target_2026-10-26_17-5-3.json (see preview_screen _performSave)
static DateTime? _timeFromFileName(File file) {
final match = RegExp(r'target_(\d+)-(\d+)-(\d+)_(\d+)-(\d+)-(\d+)\.json$')
.firstMatch(file.path);
if (match == null) return null;
final p = [for (int i = 1; i <= 6; i++) int.parse(match.group(i)!)];
return DateTime(p[0], p[1], p[2], p[3], p[4], p[5]);
}
/// Renames a session and/or changes its type. Returns false if the new name is taken.
static Future<bool> updateSession(Session session,
{required String name, required bool isTournament}) async {
final root = await _root();
var folder = Directory('${root.path}/${session.name}');
if (name != session.name) {
final target = Directory('${root.path}/$name');
if (await target.exists()) return false;
folder = await folder.rename(target.path);
}
final metaFile = File('${folder.path}/metadata.json');
final meta = await _readMetadata(folder);
await metaFile.writeAsString(jsonEncode({
'isTournament': isTournament,
'createdAt': meta['createdAt'] ?? session.date.toIso8601String(),
}));
return true;
}
static Future<void> deleteSession(Session session) async {
final folder = Directory('${(await _root()).path}/${session.name}');
if (await folder.exists()) await folder.delete(recursive: true);
}
static Future<void> deleteTarget(TargetRecord target) async {
if (await target.file.exists()) await target.file.delete();
}
}
class _FolderInfo {
final String name;
final bool isTournament;
final DateTime date;
final List<File> targetFiles;
const _FolderInfo({required this.name, required this.isTournament, required this.date, required this.targetFiles});
}