Files
SDKmuta/lib/services/target_repository.dart
T
2026-11-27 14:37:44 +01:00

369 lines
12 KiB
Dart

import 'dart:convert';
import 'dart:io';
import 'dart:math';
import 'dart:ui' show Offset;
import 'package:flutter/foundation.dart' show ValueNotifier;
import 'package:path_provider/path_provider.dart';
import '../utils/target_scoring.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});
}
/// The hits of one saved target, in target space (see [TargetScoring]).
class TargetHits {
final List<Offset> bullets;
final List<int> scores; // same order as [bullets]
final int total;
final int shots; // shots fired, misses included
final String date; // as saved: dd/MM/yyyy
const TargetHits({required this.bullets, required this.scores, required this.total, required this.shots, required this.date});
static const empty = TargetHits(bullets: [], scores: [], total: 0, shots: 0, date: '');
/// All hits of several targets on one target.
static TargetHits combine(List<TargetHits> list) => TargetHits(
bullets: [for (final t in list) ...t.bullets],
scores: [for (final t in list) ...t.scores],
total: list.fold(0, (a, t) => a + t.total),
shots: list.fold(0, (a, t) => a + t.shots),
date: list.isEmpty ? '' : list.last.date,
);
// Newer saves store each shot's score (hand-entered shots keep the score that
// was entered); older ones are scored from the positions, by the same rule.
factory TargetHits.fromJson(Map<String, dynamic> data) {
final bullets = [
for (final b in (data['bullets'] as List?) ?? const [])
Offset((b['x'] as num).toDouble(), (b['y'] as num).toDouble())
];
final saved = data['scores'];
final scores = saved is List && saved.length == bullets.length
? [for (final x in saved) (x as num).toInt()]
: [for (final b in bullets) TargetScoring.scoreAt(b)];
final total = data['totalScore'] is int ? data['totalScore'] as int : scores.fold(0, (a, b) => a + b);
return TargetHits(
bullets: bullets,
scores: scores,
total: total,
shots: (data['bulletCount'] as int?) ?? bullets.length,
date: data['date'] as String? ?? '',
);
}
}
/// 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 {
static const int trendWindow = 5;
final int sessions;
final int targets;
final int shots;
final Session? bestSession; // highest average per shot
final double? averageTarget;
final double? averagePerShot;
final double? trend; // last sessions minus the ones before them, per shot
const ShooterStats._({
required this.sessions,
required this.targets,
required this.shots,
required this.bestSession,
required this.averageTarget,
required this.averagePerShot,
required this.trend,
});
/// [sessions] newest first, as [TargetRepository.loadSessions] returns them.
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 mean = all.isEmpty ? null : total / all.length;
Session? bestSession;
for (final s in sessions) {
final avg = s.averagePerShot;
if (avg != null &&
(bestSession == null || avg > bestSession.averagePerShot!)) {
bestSession = s;
}
}
return ShooterStats._(
sessions: sessions.length,
targets: all.length,
shots: shots,
bestSession: bestSession,
averageTarget: mean,
averagePerShot: shots == 0 ? null : total / shots,
trend: _trend(sessions),
);
}
// Average per shot of the newest sessions minus the same number before them
static double? _trend(List<Session> newestFirst) {
final scored = newestFirst.where((s) => s.shots > 0).toList();
final n = min(trendWindow, scored.length ~/ 2);
if (n == 0) return null;
double avg(Iterable<Session> list) =>
list.fold(0, (a, s) => a + s.totalScore) /
list.fold(0, (a, s) => a + s.shots);
return avg(scored.take(n)) - avg(scored.skip(n).take(n));
}
}
/// Reads and edits the saved targets under `<documents>/saved_images/<session>/`.
///
/// Score and shots of every target are cached in `<documents>/target_index.json`,
/// keyed by the file's path with its size and last change, so loading reads one
/// file instead of every target. A new, edited or renamed target no longer
/// matches its entry and is read again; entries of deleted files are dropped.
class TargetRepository {
static Map<String, dynamic>? _index; // path in saved_images -> entry
/// Bumped whenever a target or session is saved, edited or deleted, so open
/// screens (Streljanje, Knjiga) reload.
static final ValueNotifier<int> changed = ValueNotifier(0);
static void notifyChanged() => changed.value++;
static Future<Directory> _root() async {
final dir = Directory(
'${(await getApplicationDocumentsDirectory()).path}/saved_images');
if (!await dir.exists()) await dir.create(recursive: true);
return dir;
}
static Future<File> _indexFile() async => File(
'${(await getApplicationDocumentsDirectory()).path}/target_index.json');
static Future<Map<String, dynamic>> _loadIndex() async {
if (_index != null) return _index!;
try {
final file = await _indexFile();
_index = await file.exists()
? jsonDecode(await file.readAsString()) as Map<String, dynamic>
: {};
} catch (_) {
_index = {}; // unreadable: rebuild it from the targets
}
return _index!;
}
/// Sessions, newest first.
static Future<List<Session>> loadSessions() async {
final sessions = <Session>[];
final index = await _loadIndex();
final seen = <String>{};
var changed = false;
for (final folder in await _folders()) {
final targets = <TargetRecord>[];
for (final file in folder.targetFiles) {
final key = '${folder.name}/${file.uri.pathSegments.last}';
seen.add(key);
final stat = file.statSync();
final stamp = '${stat.size}:${stat.modified.millisecondsSinceEpoch}';
final cached = index[key];
TargetRecord? record;
if (cached is Map && cached['stamp'] == stamp) {
record = TargetRecord(
file: file,
shotAt: _timeFromFileName(file) ?? stat.modified,
score: cached['score'] as int,
shots: cached['shots'] as int,
);
} else {
record = await _readTarget(file);
if (record != null) {
index[key] = {
'stamp': stamp,
'score': record.score,
'shots': record.shots
};
changed = true;
}
}
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,
));
}
final before = index.length;
index.removeWhere((key, _) => !seen.contains(key));
if (changed || index.length != before) {
try {
await (await _indexFile()).writeAsString(jsonEncode(index));
} catch (_) {
// Only a cache: the next load reads the targets again
}
}
sessions.sort((a, b) => b.date.compareTo(a.date));
return sessions;
}
// 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(),
}));
notifyChanged();
return true;
}
/// Hits of a saved target file; empty when it can't be read.
static Future<TargetHits> readHits(File file) async {
try {
return TargetHits.fromJson(jsonDecode(await file.readAsString()) as Map<String, dynamic>);
} catch (_) {
return TargetHits.empty;
}
}
/// Hits of several targets, in the order given.
static Future<List<TargetHits>> readAllHits(List<File> files) => Future.wait(files.map(readHits));
static Future<void> deleteSession(Session session) async {
final folder = Directory('${(await _root()).path}/${session.name}');
if (await folder.exists()) await folder.delete(recursive: true);
notifyChanged();
}
static Future<void> deleteTarget(TargetRecord target) async {
if (await target.file.exists()) await target.file.delete();
notifyChanged();
}
}
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});
}