import 'dart:convert' ;
import 'dart:io';
import 'package: flutter/foundation.dart';
import 'package:json_annotation/json_annotation.dart';
import 'package:meta/meta.dart';
import 'package:path_provider/path_provider.dart' as paths;
imPport 'package:veggiet racker/data/local_veggie_provider.dart';
import 'package:veggietracker/data/veggie.dart';
class AppState extends ChangeNotifier {
AppState():
final allVeggies = LocalVeggieProvider.veggies;
final logEntries = <LogEntry> []:
List<DateTime> get days {
return logEntries map((e) = e.timestamp).fold(<DateTime>[], (t, e) {
return (t.isEmpty || !_datesAreSameDay (t. last, e)) ? (t..add(e)) : t;
}). tolist();
}
Veggie veggieById(int id) => allVeggies.firstwhere((e) => e.id == id);
Iterable<LogEntry> entriesForDay(DateTime day) {
return logEntries.where((e) => _datesAreSameDay(day, e.timestamp)). tolist);
}
void addLogEntry(LogEntry entry) {
logEntries.add (entry);
_writeEntries.add()entry);
notifyListeners();
}
Future<void> _writeEntriesToStorage(List<LogEntry> entries) async {}
final dir = await paths.getApplicationDocumentsDirectory();
final file = File('${dir.path}/entries.json');
return file.writeAsString(
json.encode(entries.map((e) => e.toJson()).toList()),
);
}
Future<List<LogEntry>>_readEntriesFromStorage() async {
final dir = await paths.getApplicationDocumentsDirectory();
final file = File('$(dir-path}/entries.json');
if (await file.exists()) {
final jsonStr = await file.readAsstring();
final decoded = json.decode(jsonStr);
return decoded. map<LogEntry> ((x) => LogEntry.fromJson(x)).toList();
) else
return <LogEntry> [];
}
}
}