mirrored_repositories/Expenses_Tracker_App/lib/bloc
import 'package:bloc/bloc.dart';
import 'package:equatable/equatable.dart';
import 'package:expense_repository/expense_repository.dart';

part 'get_expenses_event.dart';
part 'get_expenses_state.dart';

class GetExpensesBloc extends Bloc<GetExpensesEvent, GetExpensesState> {
  ExpenseRepository expenseRepository;

  GetExpensesBloc(this.expenseRepository) : super(GetExpensesInitial()) {
    on<GetExpenses>((event, emit) async {
      emit(GetExpensesLoading());
      try {
        List<Expense> expenses =
            await expenseRepository.getExpenses(event.expense);
        emit(GetExpensesSuccess(expenses));
      } catch (e, stackTrace) {
        print('Hata: $e');
        print('Stack Trace: $stackTrace');
        emit(GetExpensesFailure());
      }
    });

    on<ExpensesUpdate>((event, emit) async {
      emit(GetExpensesLoading());
      final currentState = state;

      if (currentState is GetExpensesSuccess) {
        emit(GetExpensesSuccess(currentState.expenses));
      }
    });

    on<ExpensesDelete>((event, emit) async {
      emit(GetExpensesLoading());
      try {
        // Silme işlemini gerçekleştir
        await expenseRepository.deleteExpenses(event.expense);
        // Silme işlemi başarılıysa, mevcut harcamaları yeniden yükle
        final currentState = state;
        if (currentState is GetExpensesSuccess) {
          List<Expense> expenses =
              await expenseRepository.getExpenses(event.expense);
          emit(GetExpensesSuccess(expenses));
        }
      } catch (e, stackTrace) {
        print('Hata: $e');
        print('Stack Trace: $stackTrace');
        emit(GetExpensesFailure());
      }
    });

    on<UndoDeleteExpense>((event, emit) async {
      emit(GetExpensesLoading());
      try {
        await expenseRepository.createExpense(event.deletedExpense);

        final currentState = state;
        if (currentState is GetExpensesSuccess) {
          List<Expense> expenses =
              await expenseRepository.getExpenses(event.deletedExpense);
          emit(GetExpensesSuccess(expenses));
        }
      } catch (e, stackTrace) {
        print('Hata: $e');
        print('Stack Trace: $stackTrace');
        emit(GetExpensesFailure());
      }
    });
  }
}
