import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:kalodings/storage/storage.dart'; import 'package:uuid/uuid.dart'; class FoodEntryBloc extends Bloc { final FoodStorage storage; FoodEntryBloc(super.initialState, {required this.storage}) { on(addFoodEntry); on(deleteFood); on(updateEntries); on(persistDailyLimit); } void addFoodEntry(FoodEntryEvent event, Emitter emit) async { FoodEntryState newState = FoodEntryState.from(state); newState.addEntry(event.entry); await storage.writeEntriesForDate(event.date, newState.foodEntries); emit(newState); } void deleteFood(FoodDeletionEvent event, Emitter emit) async { state.foodEntries.removeWhere((entry) => entry.id == event.entryID); await storage.writeEntriesForDate(event.date, state.foodEntries); emit(FoodEntryState.from(state)); } void updateEntries( PageChangedEvent event, Emitter emit) async { var entries = await storage.getEntriesForDate(event.changedToDate); var limit = await storage.readLimit(); var newState = FoodEntryState(foodEntries: entries, kcalLimit: limit); emit(newState); } void persistDailyLimit( DailyKcalLimitUpdated event, Emitter emit) async { await storage.updateLimit(event.kcal); emit(FoodEntryState(foodEntries: state.foodEntries, kcalLimit: event.kcal)); } void getDailyLimit( DailyKcalLimitUpdated event, Emitter emit) async {} } class FoodEvent {} class FoodEntryEvent extends FoodEvent { final FoodEntry entry; final DateTime date; FoodEntryEvent({required this.entry, required this.date}); } class FoodDeletionEvent extends FoodEvent { final String entryID; final DateTime date; FoodDeletionEvent({required this.entryID, required this.date}); } class PageChangedEvent extends FoodEvent { final DateTime changedToDate; PageChangedEvent({required this.changedToDate}); } class DailyKcalLimitUpdated extends FoodEvent { final double kcal; DailyKcalLimitUpdated({required this.kcal}); } class FoodEntryState { final List foodEntries; final double kcalLimit; FoodEntryState({required this.foodEntries, required this.kcalLimit}); factory FoodEntryState.init() { return FoodEntryState(foodEntries: [], kcalLimit: 0); } static from(FoodEntryState state) { List newList = List.from(state.foodEntries); return FoodEntryState(foodEntries: newList, kcalLimit: state.kcalLimit); } void addEntry(FoodEntry entry) { foodEntries.add(entry); } } class FoodEntry { final String name; final double mass; final double kcalPerMass; final String id; FoodEntry({ required this.name, required this.mass, required this.kcalPerMass, }) : id = const Uuid().v1(); @override String toString() { return '$id,$name,$mass,$kcalPerMass'; } }