import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:hl_lieferservice/feature/cars/repository/cars_repository.dart'; import 'package:hl_lieferservice/widget/operations/bloc/operation_bloc.dart'; import 'package:hl_lieferservice/widget/operations/bloc/operation_event.dart'; import '../../../model/car.dart'; import 'cars_event.dart'; import 'cars_state.dart'; class CarsBloc extends Bloc { CarsRepository repository; OperationBloc opBloc; CarsBloc({required this.repository, required this.opBloc}) : super(CarsInitial()) { on(_carAdd); on(_carEdit); on(_carDelete); on(_carLoad); } Future _carLoad(CarLoad event, Emitter emit) async { try { emit(CarsLoading()); List cars = await repository.getAll(event.teamId); emit(CarsLoaded(cars: cars, teamId: event.teamId)); } catch (e) { emit(CarsLoadingFailed()); } } Future _carAdd(CarAdd event, Emitter emit) async { final currentState = state; try { opBloc.add(LoadOperation()); Car newCar = await repository.add(event.teamId, event.plate); if (currentState is CarsLoaded) { emit( currentState.copyWith( cars: List.from(currentState.cars)..add(newCar), ), ); } opBloc.add(FinishOperation(message: "Auto erfolgreich hinzugefügt")); } catch (e) { opBloc.add(FailOperation(message: "Fehler beim Hinzufügen eines Autos")); } } Future _carEdit(CarEdit event, Emitter emit) async { final currentState = state; try { opBloc.add(LoadOperation()); await repository.edit(event.teamId, event.newCar); if (currentState is CarsLoaded) { emit( currentState.copyWith( cars: List.from(currentState.cars).map((car) { if (car.id == event.newCar.id) { return event.newCar; } return car; }).toList(), ), ); } opBloc.add(FinishOperation(message: "Auto erfolgreich editiert")); } catch (e) { opBloc.add(FailOperation(message: "Fehler beim Editieren des Autos")); } } Future _carDelete(CarDelete event, Emitter emit) async { final currentState = state; try { opBloc.add(LoadOperation()); await repository.delete(event.carId, event.teamId); if (currentState is CarsLoaded) { emit( CarsLoaded( cars: [ ...currentState.cars.where( (car) => car.id != int.parse(event.carId), ), ], teamId: currentState.teamId, ), ); } opBloc.add(FinishOperation(message: "Auto erfolgreich gelöscht")); } catch (e) { opBloc.add(FailOperation(message: "Fehler beim Löschen des Autos")); } } }