import 'package:bloc/bloc.dart';
import 'package:equatable/equatable.dart';
import 'package:syncrow_web/pages/access_management/manage_bookable_spaces/domain/models/bookable_space_model.dart';
import 'package:syncrow_web/pages/access_management/manage_bookable_spaces/domain/params/bookable_spaces_params.dart';
import 'package:syncrow_web/pages/access_management/manage_bookable_spaces/domain/service/bookable_spaces_service.dart';
import 'package:syncrow_web/pages/space_management_v2/main_module/shared/models/paginated_data_model.dart';
import 'package:syncrow_web/services/api/api_exception.dart';

part 'bookable_spaces_event.dart';
part 'bookable_spaces_state.dart';

class BookableSpacesBloc
    extends Bloc<BookableSpacesEvent, BookableSpacesState> {
  final BookableSpacesService bookableSpacesService;
  BookableSpacesBloc(this.bookableSpacesService)
      : super(BookableSpacesInitial()) {
    on<LoadBookableSpacesEvent>(_onLoadBookableSpaces);
  }

  Future<void> _onLoadBookableSpaces(
      LoadBookableSpacesEvent event, Emitter<BookableSpacesState> emit) async {
    emit(BookableSpacesLoading());
    try {
      final bookableSpaces = await bookableSpacesService.load(event.params);
      emit(BookableSpacesLoaded(bookableSpacesList: bookableSpaces));
    } on APIException catch (e) {
      emit(BookableSpacesError(error: e.message));
    } catch (e) {
      emit(
        BookableSpacesError(error: e.toString()),
      );
    }
  }
}
