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<CarEvents, CarsState> {
  CarsRepository repository;
  OperationBloc opBloc;

  CarsBloc({required this.repository, required this.opBloc})
    : super(CarsInitial()) {
    on<CarAdd>(_carAdd);
    on<CarEdit>(_carEdit);
    on<CarDelete>(_carDelete);
    on<CarLoad>(_carLoad);
  }

  Future<void> _carLoad(CarLoad event, Emitter<CarsState> emit) async {
    try {
      emit(CarsLoading());
      List<Car> cars = await repository.getAll(event.teamId);
      emit(CarsLoaded(cars: cars, teamId: event.teamId));
    } catch (e) {
      emit(CarsLoadingFailed());
    }
  }

  Future<void> _carAdd(CarAdd event, Emitter<CarsState> 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<Car>.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<void> _carEdit(CarEdit event, Emitter<CarsState> 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<Car>.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<void> _carDelete(CarDelete event, Emitter<CarsState> 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"));
    }
  }
}
