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

279 lines
10 KiB
Dart
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import 'package:flutter/material.dart';
import 'package:intl/intl.dart';
import '../services/app_settings.dart';
import '../services/target_repository.dart';
import '../theme/app_theme.dart';
import '../utils/format.dart';
import '../widgets/section.dart';
import '../widgets/target_face.dart';
import '../widgets/ui.dart';
import 'target_view.dart';
/// One training or tournament: its stats, its targets, and edit/delete actions.
class SessionScreen extends StatefulWidget {
final Session session;
const SessionScreen({super.key, required this.session});
@override
State<SessionScreen> createState() => _SessionScreenState();
}
class _SessionScreenState extends State<SessionScreen> {
late Session _session = widget.session;
Map<String, TargetHits> _hits = {}; // file path -> hits, for the thumbnails
@override
void initState() {
super.initState();
_loadHits();
}
Future<void> _loadHits() async {
final files = _session.files;
final all = await TargetRepository.readAllHits(files);
if (!mounted) return;
setState(() => _hits = {for (int i = 0; i < files.length; i++) files[i].path: all[i]});
}
Future<void> _reload() async {
final sessions = await TargetRepository.loadSessions();
final updated = sessions.where((s) => s.name == _session.name);
if (!mounted) return;
if (updated.isEmpty) {
Navigator.pop(context); // session no longer exists
} else {
setState(() => _session = updated.first);
_loadHits();
}
}
void _openTargets(List<TargetRecord> targets) {
Navigator.push(
context,
MaterialPageRoute(
builder: (_) => TargetViewScreen(
jsonFiles: [for (final t in targets) t.file],
refreshFolders: _reload,
),
),
);
}
Future<void> _edit() async {
final result = await showEditSessionDialog(context, _session);
if (result == null) return;
final ok = await TargetRepository.updateSession(_session, name: result.name, isTournament: result.isTournament);
if (!mounted) return;
if (!ok) {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(content: Text(AppSettings.instance.t('A folder with this name already exists'))),
);
return;
}
_session = Session(name: result.name, isTournament: result.isTournament, date: _session.date, targets: _session.targets);
_reload();
}
Future<void> _delete() async {
final s = AppSettings.instance;
final message = '${s.t('Are you sure you want to delete the folder')} »${_session.name}« ${s.t('and all of its contents?')}';
if (!await confirmDelete(context, message)) return;
await TargetRepository.deleteSession(_session);
if (mounted) Navigator.pop(context);
}
Future<void> _deleteTarget(TargetRecord target) async {
if (!await confirmDelete(context, AppSettings.instance.t('Are you sure you want to delete this file?'))) return;
await TargetRepository.deleteTarget(target);
_reload();
}
@override
Widget build(BuildContext context) {
return ListenableBuilder(
listenable: AppSettings.instance,
builder: (context, _) {
final s = AppSettings.instance;
final t = s.t;
final c = Palette.current;
final session = _session;
final stats = ShooterStats.of([session]);
final best = session.targets.isEmpty ? null : session.targets.map((x) => x.score).reduce((a, b) => a > b ? a : b);
return Scaffold(
body: Column(
children: [
BackHeader(
title: session.name,
actions: [
CircleButton(icon: Icons.edit_outlined, tooltip: t('Edit'), onTap: _edit),
CircleButton(
icon: Icons.delete_outline_rounded,
tooltip: t('Delete'),
color: c.red,
background: c.redSoft,
onTap: _delete,
),
],
),
Expanded(
child: ListView(
// Keep the last row clear of the system gesture bar (edge-to-edge)
padding: EdgeInsets.fromLTRB(AppTheme.edge, 4, AppTheme.edge, 24 + MediaQuery.paddingOf(context).bottom),
children: [
Kicker(
'${session.isTournament ? t('Tournament') : t('Training')} · ${DateFormat('d. M. yyyy').format(session.date)}',
padding: const EdgeInsets.only(bottom: 10),
),
StatGrid(tiles: [
StatTile(label: t('Total'), value: '${session.totalScore}', caption: targetCount(session.targets.length)),
StatTile(
label: t('Average per shot'),
value: stats.averagePerShot == null ? '–' : dec(stats.averagePerShot!),
caption: shotCount(stats.shots),
),
]),
SectionHeader(t('Targets')),
if (session.targets.isEmpty)
Padding(
padding: const EdgeInsets.all(16),
child: Text(t('No targets in this folder'), style: TextStyle(color: c.muted)),
)
else
for (int i = 0; i < session.targets.length; i++)
Padding(
padding: const EdgeInsets.only(bottom: 10),
child: _targetRow(s, c, i, session.targets[i], session.targets[i].score == best),
),
],
),
),
],
),
);
},
);
}
Widget _targetRow(AppSettings s, Palette c, int i, TargetRecord target, bool isBest) {
return AppCard(
padding: const EdgeInsets.fromLTRB(10, 10, 4, 10),
onTap: () => _openTargets([target]),
child: Row(
children: [
SizedBox.square(
dimension: 44,
child: TargetFace(
style: s.target,
hits: _hits[target.file.path]?.bullets ?? const [],
hitColor: s.bulletColor,
),
),
const SizedBox(width: 12),
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text('${s.t('Target')} ${i + 1}', style: TextStyle(fontSize: 15, fontWeight: FontWeight.w700, color: c.ink)),
const SizedBox(height: 2),
Text('${DateFormat('HH:mm').format(target.shotAt)} · ${shotCount(target.shots)}',
style: TextStyle(fontSize: 12, color: c.muted)),
],
),
),
Text('${target.score}',
style: TextStyle(
fontSize: 20,
fontWeight: FontWeight.w800,
color: isBest ? (c.isDark ? c.gold : c.goldInk) : c.ink,
fontFeatures: AppTheme.tnum)),
IconButton(
icon: Icon(Icons.delete_outline_rounded, color: c.red, size: 20),
onPressed: () => _deleteTarget(target),
),
],
),
);
}
}
/// "1 target" / "5 targets", with Slovenian dual and plural forms.
String targetCount(int n) {
final s = AppSettings.instance;
if (s.language == 'German') return n == 1 ? '1 Scheibe' : '$n Scheiben';
if (s.language != 'Slovenian') return n == 1 ? '1 target' : '$n targets';
final mod = n % 100;
final word = mod == 1 ? 'tarča' : mod == 2 ? 'tarči' : (mod == 3 || mod == 4) ? 'tarče' : 'tarč';
return '$n $word';
}
/// "1 shot" / "5 shots", with Slovenian dual and plural forms.
String shotCount(int n) {
final s = AppSettings.instance;
if (s.language == 'German') return n == 1 ? '1 Schuss' : '$n Schüsse';
if (s.language != 'Slovenian') return n == 1 ? '1 shot' : '$n shots';
final mod = n % 100;
final word = mod == 1 ? 'strel' : mod == 2 ? 'strela' : (mod == 3 || mod == 4) ? 'streli' : 'strelov';
return '$n $word';
}
/// "Potrdi brisanje" dialog. True when confirmed.
Future<bool> confirmDelete(BuildContext context, String message) {
final s = AppSettings.instance;
return confirmDialog(context, title: s.t('Confirm Deletion'), message: message, confirm: s.t('Yes, delete'));
}
class SessionEdit {
final String name;
final bool isTournament;
const SessionEdit(this.name, this.isTournament);
}
/// Rename a session and choose training/tournament ("Nastavitve mape").
Future<SessionEdit?> showEditSessionDialog(BuildContext context, Session session) {
final s = AppSettings.instance;
final controller = TextEditingController(text: session.name);
var isTournament = session.isTournament;
return showDialog<SessionEdit>(
context: context,
builder: (dialog) => StatefulBuilder(
builder: (context, setDialogState) {
final c = Palette.current;
return AppDialog(
title: s.t('Folder Settings'),
content: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
TextField(controller: controller, style: TextStyle(color: c.ink, fontSize: 15)),
const SizedBox(height: 12),
ToggleRow(
icon: Icons.emoji_events_outlined,
label: s.t('Tournament'),
value: isTournament,
onChanged: (v) => setDialogState(() => isTournament = v),
),
const SizedBox(height: 10),
Text(s.t('Rename the session or move it to tournaments.'), style: TextStyle(fontSize: 12, color: c.muted)),
],
),
actions: [
DialogTextButton(s.t('Cancel'), onTap: () => Navigator.pop(dialog)),
PrimaryButton(
label: s.t('Save'),
height: 46,
onTap: () {
final name = controller.text.trim();
if (name.isEmpty || name.contains('/')) return;
Navigator.pop(dialog, SessionEdit(name, isTournament));
},
),
],
);
},
),
);
}