68 lines
2.2 KiB
Dart
68 lines
2.2 KiB
Dart
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<Directory> Function()? documentsDirectoryProvider,
|
|
}) : _bundle = bundle ?? rootBundle,
|
|
_documentsDirectoryProvider =
|
|
documentsDirectoryProvider ?? getApplicationDocumentsDirectory;
|
|
|
|
final AssetBundle _bundle;
|
|
final Future<Directory> Function() _documentsDirectoryProvider;
|
|
|
|
Future<List<Match>> loadSourceMatches() async {
|
|
final contents = await _bundle.loadString('lib/data/results.json');
|
|
final data = jsonDecode(contents) as Map<String, dynamic>;
|
|
return (data['games'] as List<dynamic>)
|
|
.map((game) => Match.fromJson(game as Map<String, dynamic>))
|
|
.toList();
|
|
}
|
|
|
|
Future<StoredMatchData> loadStoredData() async {
|
|
final file = await _storageFile();
|
|
if (!await file.exists()) {
|
|
return const StoredMatchData(matches: [], sourceCursor: 0);
|
|
}
|
|
|
|
final data = jsonDecode(await file.readAsString()) as Map<String, dynamic>;
|
|
final storedMatches = data['matches'] as List<dynamic>? ?? const [];
|
|
final sourceCursor = data['sourceCursor'];
|
|
|
|
return StoredMatchData(
|
|
matches: storedMatches
|
|
.map((match) => Match.fromJson(match as Map<String, dynamic>))
|
|
.toList(),
|
|
sourceCursor: sourceCursor is int && sourceCursor >= 0 ? sourceCursor : 0,
|
|
);
|
|
}
|
|
|
|
Future<void> saveStoredData(List<Match> matches, int sourceCursor) async {
|
|
final file = await _storageFile();
|
|
await file.writeAsString(
|
|
jsonEncode({
|
|
'sourceCursor': sourceCursor,
|
|
'matches': matches.map((match) => match.toJson()).toList(),
|
|
}),
|
|
flush: true,
|
|
);
|
|
}
|
|
|
|
Future<File> _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<Match> matches;
|
|
final int sourceCursor;
|
|
} |