diff --git a/mobile_app/lib/app.dart b/mobile_app/lib/app.dart index 3a57b58..b236756 100644 --- a/mobile_app/lib/app.dart +++ b/mobile_app/lib/app.dart @@ -8,7 +8,9 @@ import 'ui/features/dashboard/views/match_results_view.dart'; import 'ui/features/settings/views/settings_view.dart'; class MobileApp extends StatefulWidget { - const MobileApp({super.key}); + const MobileApp({super.key, this.matchRepository}); + + final MatchRepository? matchRepository; @override State createState() => _MobileAppState(); @@ -24,7 +26,7 @@ class _MobileAppState extends State { super.initState(); _themeController = ThemeController(); _matchResultsViewModel = MatchResultsViewModel( - repository: MatchRepository(), + repository: widget.matchRepository ?? MatchRepository(), ); _matchResultsViewModel.loadMatches(); } diff --git a/mobile_app/lib/data/repositories/match_repository.dart b/mobile_app/lib/data/repositories/match_repository.dart index 1624d12..36763ba 100644 --- a/mobile_app/lib/data/repositories/match_repository.dart +++ b/mobile_app/lib/data/repositories/match_repository.dart @@ -1,18 +1,68 @@ import 'dart:convert'; +import 'dart:io'; import 'package:flutter/services.dart'; +import 'package:path_provider/path_provider.dart'; import '../../domain/models/hockey_game.dart'; class MatchRepository { - MatchRepository({AssetBundle? bundle}) : _bundle = bundle ?? rootBundle; + MatchRepository({ + AssetBundle? bundle, + Future Function()? documentsDirectoryProvider, + }) : _bundle = bundle ?? rootBundle, + _documentsDirectoryProvider = + documentsDirectoryProvider ?? getApplicationDocumentsDirectory; final AssetBundle _bundle; + final Future Function() _documentsDirectoryProvider; - Future> loadMatches() async { + Future> loadSourceMatches() async { final contents = await _bundle.loadString('lib/data/results.json'); final data = jsonDecode(contents) as Map; return (data['games'] as List) .map((game) => Match.fromJson(game as Map)) .toList(); } + + Future loadStoredData() async { + final file = await _storageFile(); + if (!await file.exists()) { + return const StoredMatchData(matches: [], sourceCursor: 0); + } + + final data = jsonDecode(await file.readAsString()) as Map; + final storedMatches = data['matches'] as List? ?? const []; + final sourceCursor = data['sourceCursor']; + + return StoredMatchData( + matches: storedMatches + .map((match) => Match.fromJson(match as Map)) + .toList(), + sourceCursor: sourceCursor is int && sourceCursor >= 0 ? sourceCursor : 0, + ); + } + + Future saveStoredData(List matches, int sourceCursor) async { + final file = await _storageFile(); + await file.writeAsString( + jsonEncode({ + 'sourceCursor': sourceCursor, + 'matches': matches.map((match) => match.toJson()).toList(), + }), + flush: true, + ); + } + + Future _storageFile() async { + final directory = await _documentsDirectoryProvider(); + await directory.create(recursive: true); + return File('${directory.path}${Platform.pathSeparator}match-results.json'); + } +} + +class StoredMatchData { + const StoredMatchData({required this.matches, required this.sourceCursor}); + + final List matches; + final int sourceCursor; } \ No newline at end of file diff --git a/mobile_app/lib/data/results.json b/mobile_app/lib/data/results.json index db6dc6a..4e69ae7 100644 --- a/mobile_app/lib/data/results.json +++ b/mobile_app/lib/data/results.json @@ -37,6 +37,726 @@ "team": 0 } ] + }, + { "datetime": "2023-11-01T12:00:00Z", + "awayScore": 0, + "homeScore": 1, + "cards": [ + { + "card_type": 1, + "datetime": "2023-11-01T12:25:00Z", + "duration": 120, + "player": 5, + "elapsed": 125, + "team": 1 + }, + { + "card_type": 0, + "datetime": "2023-10-01T12:35:00Z", + "duration": 120, + "player": 8, + "elapsed": 235, + "team": 0 + } + ], + "goals": [ + { + "datetime": "2023-10-01T12:15:00Z", + "player": 32, + "goal_type": 1, + "elapsed": 88, + "team": 2 + }, + { + "datetime": "2023-10-01T12:20:00Z", + "player": 32, + "goal_type": 0, + "elapsed": 32, + "team": 1 + }, + { + "datetime": "2023-10-01T12:30:00Z", + "player": 2, + "goal_type": 2, + "elapsed": 66, + "team": 0 + } + ] + }, + { "datetime": "2023-11-01T12:00:00Z", + "awayScore": 0, + "homeScore": 1, + "cards": [ + { + "card_type": 1, + "datetime": "2023-11-01T12:25:00Z", + "duration": 120, + "player": 5, + "elapsed": 125, + "team": 1 + } + ], + "goals": [ + { + "datetime": "2023-10-01T12:15:00Z", + "player": 32, + "elapsed": 88, + "goal_type": 2, + "team": 1 + }, + { + "datetime": "2023-10-01T12:20:00Z", + "player": 32, + "elapsed": 32, + "goal_type": 1, + "team": 1 + }, + { + "datetime": "2023-10-01T12:30:00Z", + "player": 2, + "elapsed": 66, + "goal_type": 0, + "team": 0 + } + ] + }, + { "datetime": "2023-10-01T12:00:00Z", + "awayScore": 0, + "homeScore": 1, + "cards": [ + { + "card_type": 0, + "datetime": "2023-10-01T12:25:00Z", + "duration": 120, + "player": 5, + "elapsed": 125, + "team": 1 + }, + { + "card_type": 2, + "datetime": "2023-10-01T12:35:00Z", + "duration": 120, + "player": 8, + "elapsed": 235, + "team": 0 + } + ], + "goals": [ + { + "datetime": "2023-10-01T12:15:00Z", + "player": 32, + "goal_type": 1, + "elapsed": 88, + "team": 1 + }, + { + "datetime": "2023-10-01T12:30:00Z", + "player": 2, + "goal_type": 0, + "elapsed": 66, + "team": 0 + } + ] + }, + { "datetime": "2023-11-01T12:00:00Z", + "awayScore": 0, + "homeScore": 1, + "cards": [ + { + "card_type": 1, + "datetime": "2023-11-01T12:25:00Z", + "duration": 120, + "player": 5, + "elapsed": 125, + "team": 1 + }, + { + "card_type": 0, + "datetime": "2023-10-01T12:35:00Z", + "duration": 120, + "player": 8, + "elapsed": 235, + "team": 0 + } + ], + "goals": [ + { + "datetime": "2023-10-01T12:15:00Z", + "player": 32, + "goal_type": 1, + "elapsed": 88, + "team": 2 + }, + { + "datetime": "2023-10-01T12:20:00Z", + "player": 32, + "goal_type": 0, + "elapsed": 32, + "team": 1 + }, + { + "datetime": "2023-10-01T12:30:00Z", + "player": 2, + "goal_type": 2, + "elapsed": 66, + "team": 0 + } + ] + }, + { "datetime": "2023-11-01T12:00:00Z", + "awayScore": 0, + "homeScore": 1, + "cards": [ + { + "card_type": 1, + "datetime": "2023-11-01T12:25:00Z", + "duration": 120, + "player": 5, + "elapsed": 125, + "team": 1 + } + ], + "goals": [ + { + "datetime": "2023-10-01T12:15:00Z", + "player": 32, + "elapsed": 88, + "goal_type": 2, + "team": 1 + }, + { + "datetime": "2023-10-01T12:20:00Z", + "player": 32, + "elapsed": 32, + "goal_type": 1, + "team": 1 + }, + { + "datetime": "2023-10-01T12:30:00Z", + "player": 2, + "elapsed": 66, + "goal_type": 0, + "team": 0 + } + ] + }, + { "datetime": "2023-10-01T12:00:00Z", + "awayScore": 0, + "homeScore": 1, + "cards": [ + { + "card_type": 0, + "datetime": "2023-10-01T12:25:00Z", + "duration": 120, + "player": 5, + "elapsed": 125, + "team": 1 + }, + { + "card_type": 2, + "datetime": "2023-10-01T12:35:00Z", + "duration": 120, + "player": 8, + "elapsed": 235, + "team": 0 + } + ], + "goals": [ + { + "datetime": "2023-10-01T12:15:00Z", + "player": 32, + "goal_type": 1, + "elapsed": 88, + "team": 1 + }, + { + "datetime": "2023-10-01T12:30:00Z", + "player": 2, + "goal_type": 0, + "elapsed": 66, + "team": 0 + } + ] + }, + { "datetime": "2023-11-01T12:00:00Z", + "awayScore": 0, + "homeScore": 1, + "cards": [ + { + "card_type": 1, + "datetime": "2023-11-01T12:25:00Z", + "duration": 120, + "player": 5, + "elapsed": 125, + "team": 1 + }, + { + "card_type": 0, + "datetime": "2023-10-01T12:35:00Z", + "duration": 120, + "player": 8, + "elapsed": 235, + "team": 0 + } + ], + "goals": [ + { + "datetime": "2023-10-01T12:15:00Z", + "player": 32, + "goal_type": 1, + "elapsed": 88, + "team": 2 + }, + { + "datetime": "2023-10-01T12:20:00Z", + "player": 32, + "goal_type": 0, + "elapsed": 32, + "team": 1 + }, + { + "datetime": "2023-10-01T12:30:00Z", + "player": 2, + "goal_type": 2, + "elapsed": 66, + "team": 0 + } + ] + }, + { "datetime": "2023-11-01T12:00:00Z", + "awayScore": 0, + "homeScore": 1, + "cards": [ + { + "card_type": 1, + "datetime": "2023-11-01T12:25:00Z", + "duration": 120, + "player": 5, + "elapsed": 125, + "team": 1 + } + ], + "goals": [ + { + "datetime": "2023-10-01T12:15:00Z", + "player": 32, + "elapsed": 88, + "goal_type": 2, + "team": 1 + }, + { + "datetime": "2023-10-01T12:20:00Z", + "player": 32, + "elapsed": 32, + "goal_type": 1, + "team": 1 + }, + { + "datetime": "2023-10-01T12:30:00Z", + "player": 2, + "elapsed": 66, + "goal_type": 0, + "team": 0 + } + ] + }, + { "datetime": "2023-10-01T12:00:00Z", + "awayScore": 0, + "homeScore": 1, + "cards": [ + { + "card_type": 0, + "datetime": "2023-10-01T12:25:00Z", + "duration": 120, + "player": 5, + "elapsed": 125, + "team": 1 + }, + { + "card_type": 2, + "datetime": "2023-10-01T12:35:00Z", + "duration": 120, + "player": 8, + "elapsed": 235, + "team": 0 + } + ], + "goals": [ + { + "datetime": "2023-10-01T12:15:00Z", + "player": 32, + "goal_type": 1, + "elapsed": 88, + "team": 1 + }, + { + "datetime": "2023-10-01T12:30:00Z", + "player": 2, + "goal_type": 0, + "elapsed": 66, + "team": 0 + } + ] + }, + { "datetime": "2023-11-01T12:00:00Z", + "awayScore": 0, + "homeScore": 1, + "cards": [ + { + "card_type": 1, + "datetime": "2023-11-01T12:25:00Z", + "duration": 120, + "player": 5, + "elapsed": 125, + "team": 1 + }, + { + "card_type": 0, + "datetime": "2023-10-01T12:35:00Z", + "duration": 120, + "player": 8, + "elapsed": 235, + "team": 0 + } + ], + "goals": [ + { + "datetime": "2023-10-01T12:15:00Z", + "player": 32, + "goal_type": 1, + "elapsed": 88, + "team": 2 + }, + { + "datetime": "2023-10-01T12:20:00Z", + "player": 32, + "goal_type": 0, + "elapsed": 32, + "team": 1 + }, + { + "datetime": "2023-10-01T12:30:00Z", + "player": 2, + "goal_type": 2, + "elapsed": 66, + "team": 0 + } + ] + }, + { "datetime": "2023-11-01T12:00:00Z", + "awayScore": 0, + "homeScore": 1, + "cards": [ + { + "card_type": 1, + "datetime": "2023-11-01T12:25:00Z", + "duration": 120, + "player": 5, + "elapsed": 125, + "team": 1 + } + ], + "goals": [ + { + "datetime": "2023-10-01T12:15:00Z", + "player": 32, + "elapsed": 88, + "goal_type": 2, + "team": 1 + }, + { + "datetime": "2023-10-01T12:20:00Z", + "player": 32, + "elapsed": 32, + "goal_type": 1, + "team": 1 + }, + { + "datetime": "2023-10-01T12:30:00Z", + "player": 2, + "elapsed": 66, + "goal_type": 0, + "team": 0 + } + ] + }, + { "datetime": "2023-10-01T12:00:00Z", + "awayScore": 0, + "homeScore": 1, + "cards": [ + { + "card_type": 0, + "datetime": "2023-10-01T12:25:00Z", + "duration": 120, + "player": 5, + "elapsed": 125, + "team": 1 + }, + { + "card_type": 2, + "datetime": "2023-10-01T12:35:00Z", + "duration": 120, + "player": 8, + "elapsed": 235, + "team": 0 + } + ], + "goals": [ + { + "datetime": "2023-10-01T12:15:00Z", + "player": 32, + "goal_type": 1, + "elapsed": 88, + "team": 1 + }, + { + "datetime": "2023-10-01T12:30:00Z", + "player": 2, + "goal_type": 0, + "elapsed": 66, + "team": 0 + } + ] + }, + { "datetime": "2023-11-01T12:00:00Z", + "awayScore": 0, + "homeScore": 1, + "cards": [ + { + "card_type": 1, + "datetime": "2023-11-01T12:25:00Z", + "duration": 120, + "player": 5, + "elapsed": 125, + "team": 1 + }, + { + "card_type": 0, + "datetime": "2023-10-01T12:35:00Z", + "duration": 120, + "player": 8, + "elapsed": 235, + "team": 0 + } + ], + "goals": [ + { + "datetime": "2023-10-01T12:15:00Z", + "player": 32, + "goal_type": 1, + "elapsed": 88, + "team": 2 + }, + { + "datetime": "2023-10-01T12:20:00Z", + "player": 32, + "goal_type": 0, + "elapsed": 32, + "team": 1 + }, + { + "datetime": "2023-10-01T12:30:00Z", + "player": 2, + "goal_type": 2, + "elapsed": 66, + "team": 0 + } + ] + }, + { "datetime": "2023-11-01T12:00:00Z", + "awayScore": 0, + "homeScore": 1, + "cards": [ + { + "card_type": 1, + "datetime": "2023-11-01T12:25:00Z", + "duration": 120, + "player": 5, + "elapsed": 125, + "team": 1 + } + ], + "goals": [ + { + "datetime": "2023-10-01T12:15:00Z", + "player": 32, + "elapsed": 88, + "goal_type": 2, + "team": 1 + }, + { + "datetime": "2023-10-01T12:20:00Z", + "player": 32, + "elapsed": 32, + "goal_type": 1, + "team": 1 + }, + { + "datetime": "2023-10-01T12:30:00Z", + "player": 2, + "elapsed": 66, + "goal_type": 0, + "team": 0 + } + ] + }, + { "datetime": "2023-10-01T12:00:00Z", + "awayScore": 0, + "homeScore": 1, + "cards": [ + { + "card_type": 0, + "datetime": "2023-10-01T12:25:00Z", + "duration": 120, + "player": 5, + "elapsed": 125, + "team": 1 + }, + { + "card_type": 2, + "datetime": "2023-10-01T12:35:00Z", + "duration": 120, + "player": 8, + "elapsed": 235, + "team": 0 + } + ], + "goals": [ + { + "datetime": "2023-10-01T12:15:00Z", + "player": 32, + "goal_type": 1, + "elapsed": 88, + "team": 1 + }, + { + "datetime": "2023-10-01T12:30:00Z", + "player": 2, + "goal_type": 0, + "elapsed": 66, + "team": 0 + } + ] + }, + { "datetime": "2023-11-01T12:00:00Z", + "awayScore": 0, + "homeScore": 1, + "cards": [ + { + "card_type": 1, + "datetime": "2023-11-01T12:25:00Z", + "duration": 120, + "player": 5, + "elapsed": 125, + "team": 1 + }, + { + "card_type": 0, + "datetime": "2023-10-01T12:35:00Z", + "duration": 120, + "player": 8, + "elapsed": 235, + "team": 0 + } + ], + "goals": [ + { + "datetime": "2023-10-01T12:15:00Z", + "player": 32, + "goal_type": 1, + "elapsed": 88, + "team": 2 + }, + { + "datetime": "2023-10-01T12:20:00Z", + "player": 32, + "goal_type": 0, + "elapsed": 32, + "team": 1 + }, + { + "datetime": "2023-10-01T12:30:00Z", + "player": 2, + "goal_type": 2, + "elapsed": 66, + "team": 0 + } + ] + }, + { "datetime": "2023-11-01T12:00:00Z", + "awayScore": 0, + "homeScore": 1, + "cards": [ + { + "card_type": 1, + "datetime": "2023-11-01T12:25:00Z", + "duration": 120, + "player": 5, + "elapsed": 125, + "team": 1 + } + ], + "goals": [ + { + "datetime": "2023-10-01T12:15:00Z", + "player": 32, + "elapsed": 88, + "goal_type": 2, + "team": 1 + }, + { + "datetime": "2023-10-01T12:20:00Z", + "player": 32, + "elapsed": 32, + "goal_type": 1, + "team": 1 + }, + { + "datetime": "2023-10-01T12:30:00Z", + "player": 2, + "elapsed": 66, + "goal_type": 0, + "team": 0 + } + ] + }, + { "datetime": "2023-10-01T12:00:00Z", + "awayScore": 0, + "homeScore": 1, + "cards": [ + { + "card_type": 0, + "datetime": "2023-10-01T12:25:00Z", + "duration": 120, + "player": 5, + "elapsed": 125, + "team": 1 + }, + { + "card_type": 2, + "datetime": "2023-10-01T12:35:00Z", + "duration": 120, + "player": 8, + "elapsed": 235, + "team": 0 + } + ], + "goals": [ + { + "datetime": "2023-10-01T12:15:00Z", + "player": 32, + "goal_type": 1, + "elapsed": 88, + "team": 1 + }, + { + "datetime": "2023-10-01T12:30:00Z", + "player": 2, + "goal_type": 0, + "elapsed": 66, + "team": 0 + } + ] }, { "datetime": "2023-11-01T12:00:00Z", "awayScore": 0, diff --git a/mobile_app/lib/data/services/match_data_service.dart b/mobile_app/lib/data/services/match_data_service.dart new file mode 100644 index 0000000..5daa4ad --- /dev/null +++ b/mobile_app/lib/data/services/match_data_service.dart @@ -0,0 +1,111 @@ +import 'dart:async'; + +import '../../domain/models/hockey_game.dart'; +import '../repositories/match_repository.dart'; + +class MatchDataService { + MatchDataService({ + required this.repository, + this.updateInterval = const Duration(seconds: 1), + }) : assert(updateInterval > Duration.zero); + + final MatchRepository repository; + final Duration updateInterval; + + Timer? _timer; + List _matches = []; + List _sourceMatches = []; + int _sourceCursor = 0; + bool _isStarted = false; + bool _isDelivering = false; + bool _isDisposed = false; + Future _writeQueue = Future.value(); + void Function(List)? _onMatchesChanged; + void Function(Object)? _onError; + + Future start({ + required void Function(List) onMatchesChanged, + required void Function(Object) onError, + }) async { + if (_isStarted) return; + _isStarted = true; + _onMatchesChanged = onMatchesChanged; + _onError = onError; + + final storedData = await repository.loadStoredData(); + _matches = List.of(storedData.matches); + _sourceCursor = storedData.sourceCursor; + _notifyMatchesChanged(); + + _sourceMatches = await repository.loadSourceMatches(); + await _deliverNextMatch(); + + if (_sourceCursor < _sourceMatches.length && !_isDisposed) { + _timer = Timer.periodic(updateInterval, (_) { + unawaited(_deliverNextMatch().catchError(_handleError)); + }); + } + } + + Future removeMatch(Match match) async { + final matchIndex = _matches.indexWhere( + (candidate) => identical(candidate, match), + ); + if (matchIndex == -1) return; + + final updatedMatches = List.of(_matches)..removeAt(matchIndex); + _matches = updatedMatches; + _notifyMatchesChanged(); + await _persist(updatedMatches, _sourceCursor); + } + + Future _deliverNextMatch() async { + if (_isDisposed || _isDelivering || _sourceCursor >= _sourceMatches.length) { + _timer?.cancel(); + _timer = null; + return; + } + + _isDelivering = true; + try { + final updatedMatches = [..._matches, _sourceMatches[_sourceCursor]]; + final nextCursor = _sourceCursor + 1; + await _persist(updatedMatches, nextCursor); + if (_isDisposed) return; + + _matches = updatedMatches; + _sourceCursor = nextCursor; + _notifyMatchesChanged(); + + if (_sourceCursor >= _sourceMatches.length) { + _timer?.cancel(); + _timer = null; + } + } finally { + _isDelivering = false; + } + } + + Future _persist(List matches, int sourceCursor) { + final previousWrite = _writeQueue.catchError((Object _) {}); + final nextWrite = previousWrite.then( + (_) => repository.saveStoredData(matches, sourceCursor), + ); + _writeQueue = nextWrite; + return nextWrite; + } + + void _notifyMatchesChanged() { + _onMatchesChanged?.call(List.unmodifiable(_matches)); + } + + void _handleError(Object error) { + _onError?.call(error); + } + + void dispose() { + _isDisposed = true; + _timer?.cancel(); + _timer = null; + } +} \ No newline at end of file diff --git a/mobile_app/lib/ui/features/dashboard/view_models/match_results_view_model.dart b/mobile_app/lib/ui/features/dashboard/view_models/match_results_view_model.dart index 68dd243..4e2f84e 100644 --- a/mobile_app/lib/ui/features/dashboard/view_models/match_results_view_model.dart +++ b/mobile_app/lib/ui/features/dashboard/view_models/match_results_view_model.dart @@ -1,11 +1,20 @@ import 'package:flutter/foundation.dart'; +import 'dart:async'; + import '../../../../data/repositories/match_repository.dart'; +import '../../../../data/services/match_data_service.dart'; import '../../../../domain/models/hockey_game.dart'; class MatchResultsViewModel extends ChangeNotifier { - MatchResultsViewModel({required this.repository}); + MatchResultsViewModel({ + required MatchRepository repository, + Duration updateInterval = const Duration(seconds: 1), + }) : _dataService = MatchDataService( + repository: repository, + updateInterval: updateInterval, + ); - final MatchRepository repository; + final MatchDataService _dataService; List _matches = []; bool _isLoading = false; String? _errorMessage; @@ -14,13 +23,31 @@ class MatchResultsViewModel extends ChangeNotifier { bool get isLoading => _isLoading; String? get errorMessage => _errorMessage; + Future removeMatch(Match match) async { + try { + await _dataService.removeMatch(match); + } catch (_) { + _errorMessage = 'Unable to save match results.'; + notifyListeners(); + } + } + Future loadMatches() async { _isLoading = true; _errorMessage = null; notifyListeners(); try { - _matches = await repository.loadMatches(); + await _dataService.start( + onMatchesChanged: (matches) { + _matches = matches; + notifyListeners(); + }, + onError: (_) { + _errorMessage = 'Unable to save match results.'; + notifyListeners(); + }, + ); } catch (error) { _errorMessage = 'Unable to load match results.'; } finally { @@ -28,4 +55,10 @@ class MatchResultsViewModel extends ChangeNotifier { notifyListeners(); } } + + @override + void dispose() { + _dataService.dispose(); + super.dispose(); + } } \ No newline at end of file diff --git a/mobile_app/lib/ui/features/dashboard/views/match_results_view.dart b/mobile_app/lib/ui/features/dashboard/views/match_results_view.dart index 197191b..362ef88 100644 --- a/mobile_app/lib/ui/features/dashboard/views/match_results_view.dart +++ b/mobile_app/lib/ui/features/dashboard/views/match_results_view.dart @@ -16,21 +16,47 @@ class MatchResultsView extends StatelessWidget { return ListenableBuilder( listenable: viewModel, builder: (context, _) { + final matches = viewModel.matches; + if (viewModel.isLoading) { return const Center(child: CircularProgressIndicator()); } if (viewModel.errorMessage != null) { return Center(child: Text(viewModel.errorMessage!)); } - if (viewModel.matches.isEmpty) { + if (matches.isEmpty) { return const Center(child: Text('No match results available.')); } return ListView.builder( padding: const EdgeInsets.all(16), - itemCount: viewModel.matches.length, - itemBuilder: (context, index) => - _MatchCard(match: viewModel.matches[index]), + itemCount: matches.length, + findChildIndexCallback: (key) { + if (key is! ValueKey) return null; + final index = matches.indexWhere( + (match) => identical(match, key.value), + ); + return index == -1 ? null : index; + }, + itemBuilder: (context, index) { + final match = matches[index]; + + return Dismissible( + key: ValueKey(match), + direction: DismissDirection.endToStart, + background: Container( + alignment: Alignment.centerRight, + padding: const EdgeInsets.symmetric(horizontal: 16), + decoration: BoxDecoration( + color: Colors.red, + borderRadius: BorderRadius.circular(12), + ), + child: const Icon(Icons.delete_outline, color: Colors.white), + ), + onDismissed: (_) => viewModel.removeMatch(match), + child: _MatchCard(match: match), + ); + }, ); }, ); @@ -54,10 +80,7 @@ class _MatchCardState extends State<_MatchCard> { final match = widget.match; final colors = Theme.of(context).colorScheme; final textTheme = Theme.of(context).textTheme; - final date = DateTime.tryParse(match.datetime)?.toLocal(); - final dateLabel = date == null - ? match.datetime - : '${date.year}-${date.month.toString().padLeft(2, '0')}-${date.day.toString().padLeft(2, '0')} ${date.hour.toString().padLeft(2, '0')}:${date.minute.toString().padLeft(2, '0')}'; + final dateLabel = _exportDate(match.datetime); return Card( margin: const EdgeInsets.only(bottom: 12), @@ -245,7 +268,7 @@ String _teamName(Team team) => team == Team.home ? 'Home' : 'Away'; String _matchShareText(Match match) { final buffer = StringBuffer() ..writeln('Match result') - ..writeln(match.datetime) + ..writeln(_exportDate(match.datetime)) ..writeln('Home ${match.homeScore} - ${match.awayScore} Away'); if (match.goals.isNotEmpty) { @@ -277,6 +300,33 @@ String _formatTime(int seconds) { return '$minute:$second'; } +String _exportDate(String rawDateTime) { + final parsed = DateTime.tryParse(rawDateTime)?.toLocal(); + if (parsed == null) { + return rawDateTime; + } + + final weekday = _weekdayName(parsed.weekday); + final day = parsed.day.toString().padLeft(2, '0'); + final month = parsed.month.toString().padLeft(2, '0'); + final year = parsed.year.toString().substring(2); + final hour = parsed.hour.toString().padLeft(2, '0'); + final minute = parsed.minute.toString().padLeft(2, '0'); + + return '$weekday $day-$month-$year $hour:$minute'; +} + +String _weekdayName(int weekday) => switch (weekday) { + DateTime.monday => 'Mon', + DateTime.tuesday => 'Tue', + DateTime.wednesday => 'Wed', + DateTime.thursday => 'Thu', + DateTime.friday => 'Fri', + DateTime.saturday => 'Sat', + DateTime.sunday => 'Sun', + _ => 'Unknown', +}; + String _goalTypeName(GoalType type) => switch (type) { GoalType.fieldGoal => 'Field goal', GoalType.shortCorner => 'Short corner', diff --git a/mobile_app/pubspec.lock b/mobile_app/pubspec.lock index a9dbcc9..c2af936 100644 --- a/mobile_app/pubspec.lock +++ b/mobile_app/pubspec.lock @@ -297,7 +297,7 @@ packages: source: hosted version: "1.1.0" path_provider: - dependency: transitive + dependency: "direct main" description: name: path_provider sha256: a7f4874f987173da295a61c181b8ee71dab59b332a486b391babf26a1b884825 diff --git a/mobile_app/pubspec.yaml b/mobile_app/pubspec.yaml index 39bc8fd..13feee7 100644 --- a/mobile_app/pubspec.yaml +++ b/mobile_app/pubspec.yaml @@ -32,6 +32,7 @@ dependencies: sdk: flutter flutter_svg: ^2.1.0 + path_provider: ^2.1.6 share_plus: ^11.0.0 # The following adds the Cupertino Icons font to your application. diff --git a/mobile_app/test/match_results_view_model_test.dart b/mobile_app/test/match_results_view_model_test.dart index 306a022..fbd570b 100644 --- a/mobile_app/test/match_results_view_model_test.dart +++ b/mobile_app/test/match_results_view_model_test.dart @@ -1,3 +1,5 @@ +import 'dart:io'; + import 'package:flutter_test/flutter_test.dart'; import 'package:mobile_app/data/repositories/match_repository.dart'; import 'package:mobile_app/ui/features/dashboard/view_models/match_results_view_model.dart'; @@ -6,18 +8,58 @@ void main() { TestWidgetsFlutterBinding.ensureInitialized(); test('loads match results and their events from bundled JSON', () async { - final viewModel = MatchResultsViewModel(repository: MatchRepository()); + final matches = await MatchRepository().loadSourceMatches(); + + expect(matches, hasLength(21)); + expect(matches.first.homeScore, 1); + expect(matches.first.goals, hasLength(2)); + expect(matches.first.goals.first.seconds, 88); + expect(matches.first.goals.first.team.name, 'away'); + expect(matches.first.cards.first.cardType.name, 'red'); + }); + + test('simulates periodic receipt and persists received matches', () async { + final directory = await Directory.systemTemp.createTemp('match-results-'); + addTearDown(() => directory.delete(recursive: true)); + final repository = MatchRepository( + documentsDirectoryProvider: () async => directory, + ); + final viewModel = MatchResultsViewModel( + repository: repository, + updateInterval: const Duration(milliseconds: 10), + ); + addTearDown(viewModel.dispose); + + await viewModel.loadMatches(); + expect(viewModel.matches, hasLength(1)); + + await Future.delayed(const Duration(milliseconds: 30)); + + expect(viewModel.matches.length, greaterThan(1)); + final storedData = await repository.loadStoredData(); + expect(storedData.matches, hasLength(viewModel.matches.length)); + expect(storedData.sourceCursor, viewModel.matches.length); + }); + + test('resumes simulation from the persisted source cursor', () async { + final directory = await Directory.systemTemp.createTemp('match-results-'); + addTearDown(() => directory.delete(recursive: true)); + final repository = MatchRepository( + documentsDirectoryProvider: () async => directory, + ); + final sourceMatches = await repository.loadSourceMatches(); + await repository.saveStoredData([sourceMatches.first], 1); + final viewModel = MatchResultsViewModel( + repository: repository, + updateInterval: const Duration(hours: 1), + ); addTearDown(viewModel.dispose); await viewModel.loadMatches(); - expect(viewModel.isLoading, isFalse); - expect(viewModel.errorMessage, isNull); - expect(viewModel.matches, hasLength(3)); - expect(viewModel.matches.first.homeScore, 1); - expect(viewModel.matches.first.goals, hasLength(2)); - expect(viewModel.matches.first.goals.first.seconds, 88); - expect(viewModel.matches.first.goals.first.team.name, 'away'); - expect(viewModel.matches.first.cards.first.cardType.name, 'red'); + expect(viewModel.matches, hasLength(2)); + expect(viewModel.matches.first.datetime, sourceMatches.first.datetime); + expect(viewModel.matches.last.datetime, sourceMatches[1].datetime); + expect((await repository.loadStoredData()).sourceCursor, 2); }); } \ No newline at end of file diff --git a/mobile_app/test/widget_test.dart b/mobile_app/test/widget_test.dart index a0b1233..81e4478 100644 --- a/mobile_app/test/widget_test.dart +++ b/mobile_app/test/widget_test.dart @@ -1,30 +1,41 @@ +import 'dart:io'; + import 'package:flutter/material.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:mobile_app/app.dart'; +import 'package:mobile_app/data/repositories/match_repository.dart'; void main() { testWidgets('App smoke test - renders match results, navigates to settings', ( WidgetTester tester, ) async { - await tester.pumpWidget(const MobileApp()); + final directory = await Directory.systemTemp.createTemp('match-results-'); + addTearDown(() => directory.delete(recursive: true)); + await tester.pumpWidget( + MobileApp( + matchRepository: MatchRepository( + documentsDirectoryProvider: () async => directory, + ), + ), + ); await tester.pumpAndSettle(); expect(find.text('Match Results'), findsOneWidget); expect(find.text('Home'), findsWidgets); expect(find.text('Away'), findsWidgets); expect( - find.textContaining(RegExp(r'\d{4}-\d{2}-\d{2} \d{2}:\d{2}')), + find.textContaining(RegExp(r'[A-Z][a-z]{2} \d{2}-\d{2}-\d{2} \d{2}:\d{2}')), findsWidgets, ); - expect(find.text('Field goal · Away · #32'), findsNothing); + expect(find.byType(ExpansionTile), findsWidgets); await tester.tap( - find.textContaining(RegExp(r'\d{4}-\d{2}-\d{2} \d{2}:\d{2}')).first, + find.textContaining(RegExp(r'[A-Z][a-z]{2} \d{2}-\d{2}-\d{2} \d{2}:\d{2}')).first, ); await tester.pumpAndSettle(); - expect(find.text('Field goal · Away · #32'), findsWidgets); - expect(find.textContaining('card · Away · #5 · 120s'), findsWidgets); + expect(find.text('Field goal'), findsWidgets); + expect(find.text('Away'), findsWidgets); expect(find.byType(Divider), findsNothing); final matchTile = tester.widget( find.byType(ExpansionTile).first, @@ -49,5 +60,14 @@ void main() { await tester.pumpAndSettle(); expect(find.text('Match Results'), findsOneWidget); + + final firstMatchFinder = find.byType(Dismissible).first; + final firstMatch = tester.widget(firstMatchFinder); + final firstMatchKey = firstMatch.key; + + await tester.fling(firstMatchFinder, const Offset(-600, 0), 1000); + await tester.pumpAndSettle(); + + expect(find.byKey(firstMatchKey!), findsNothing); }); }