import 'package:food_delivery_client/food_delivery_client.dart';

part 'home_event.dart';

part 'home_state.dart';

part 'home_bloc.freezed.dart';

@injectable
class HomeBloc extends Bloc<HomeEvent, HomeState> {
  HomeBloc() : super(const HomeState()) {
    on<_Changed>(_onChanged);
    on<_Filtered>(_onFiltered);
    on<_Rated>(_onRated);
    on<_DurationChanged>(_onDurationChanged);
  }

  void _onChanged(_Changed event, Emitter<HomeState> emit) {
    emit(state.copyWith(currentIndex: event.index));
  }

  void _onFiltered(_Filtered event, Emitter<HomeState> emit) {
    final oldFilters = List.from(state.filters);
    if (oldFilters.contains(event.filter)) {
      final newFilters = oldFilters..remove(event.filter);
      emit(state.copyWith(filters: newFilters));
    } else {
      final newFilters = oldFilters..add(event.filter);
      emit(state.copyWith(filters: newFilters));
    }
  }

  void _onRated(_Rated event, Emitter<HomeState> emit) {
    emit(state.copyWith(rating: event.filter));
  }

  void _onDurationChanged(_DurationChanged event, Emitter<HomeState> emit) {
    emit(state.copyWith(deliveryDuration: event.filter));
  }
}
