import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:hl_lieferservice/feature/authentication/bloc/auth_bloc.dart'; import 'package:hl_lieferservice/feature/authentication/bloc/auth_event.dart'; import 'package:hl_lieferservice/feature/authentication/exceptions.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; AuthBloc authBloc; CarsBloc({required this.repository, required this.opBloc, required this.authBloc}) : super(CarsInitial()) { on(_carAdd); on(_carEdit); on(_carDelete); on(_carLoad); } void _handleError(Object e, String fallbackMessage) { if (e is UserUnauthorized) { authBloc.add(SessionExpiredEvent()); } else { opBloc.add(FailOperation(message: fallbackMessage)); } } Future _carLoad(CarLoad event, Emitter emit) async { // Skip the API call if cars are already loaded and no force-refresh requested. if (state is CarsLoaded && !event.force) return; try { emit(CarsLoading()); List cars = await repository.getAll(event.teamId); emit(CarsLoaded(cars: cars, teamId: event.teamId)); } catch (e) { if (e is UserUnauthorized) { authBloc.add(SessionExpiredEvent()); return; } emit(CarsLoadingFailed()); } } Future _carAdd(CarAdd event, Emitter emit) async { final currentState = state; try { 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) { _handleError(e, "Fehler beim Hinzufügen eines Autos"); } } Future _carEdit(CarEdit event, Emitter emit) async { final currentState = state; try { 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) { _handleError(e, "Fehler beim Editieren des Autos"); } } Future _carDelete(CarDelete event, Emitter emit) async { final currentState = state; try { 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) { _handleError(e, "Fehler beim Löschen des Autos"); } } }