import 'package:bloc/bloc.dart'; import 'package:Rabbit_Habit/models/habit_sammler_model.dart'; import 'package:Rabbit_Habit/models/habit_model.dart'; import 'package:Rabbit_Habit/models/selected_day_model.dart'; import 'package:Rabbit_Habit/repo/habit_repository.dart'; import 'package:hive_flutter/hive_flutter.dart'; class SelectedDayCubit extends Cubit { SelectedDayCubit() : super(SelectedDay(selectedDay: DateTime.now(), habits: [])) { changeSelectedDay( DateTime.utc( DateTime.now().year, DateTime.now().month, DateTime.now().day, ), ); } Future changeSelectedDay(DateTime newDay) async { if (newDay == state.selectedDay) return; List habits = []; Box box = await Hive.openBox('habits'); try { habits = HabitRepository(box).getHabitsForDate(newDay); } catch (e) { // add error handling to crashlytics } finally { await box.close(); } emit(state.copyWith(selectedDay: newDay, habits: habits)); } void changeHabitExpanded(int index) { List newHabits = state.habits.toList(); Rabbit habit = newHabits[index].copyWith(isExpanded: !newHabits[index].isExpanded); newHabits[index] = habit; if (newHabits != state.habits) { emit(state.copyWith(habits: newHabits)); } } Future changeHabitDone(int index) async { List newHabits = state.habits.toList(); Rabbit habit = newHabits[index].copyWith( isDone: !newHabits[index].isDone, ); Box box = await Hive.openBox('habits'); try { HabeichHabit? oldHabit = box.get(habit.id); if (oldHabit == null) return; List doneOn = oldHabit.doneOn.toList(); if (habit.isDone) { doneOn.add( state.selectedDay, ); } else { doneOn.remove(state.selectedDay); } await HabitRepository(box).updateHabit( habit.id, oldHabit.copyWith( doneOn: doneOn, updatedAt: DateTime.now(), ), ); habit = habit.copyWith( doneOn: doneOn, ); newHabits[index] = habit; } catch (e) { // add error handling to crashlytics } finally { await box.close(); } if (newHabits != state.habits) { emit(state.copyWith(habits: newHabits)); } } }