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, Future Function()? documentsDirectoryProvider, }) : _bundle = bundle ?? rootBundle, _documentsDirectoryProvider = documentsDirectoryProvider ?? getApplicationDocumentsDirectory; final AssetBundle _bundle; final Future Function() _documentsDirectoryProvider; 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; }