import 'package:bloc/bloc.dart';
import 'package:equatable/equatable.dart';
import 'package:syncrow_web/pages/space_management_v2/modules/space_details/domain/models/space_details_model.dart';
import 'package:syncrow_web/pages/space_management_v2/modules/space_details/domain/params/load_spaces_param.dart';
import 'package:syncrow_web/pages/space_management_v2/modules/space_details/domain/services/space_details_service.dart';
import 'package:syncrow_web/services/api/api_exception.dart';

part 'space_details_event.dart';
part 'space_details_state.dart';

class SpaceDetailsBloc extends Bloc<SpaceDetailsEvent, SpaceDetailsState> {
  final SpaceDetailsService _spaceDetailsService;

  SpaceDetailsBloc(this._spaceDetailsService) : super(SpaceDetailsInitial()) {
    on<LoadSpaceDetails>(_onLoadSpaceDetails);
  }

  Future<void> _onLoadSpaceDetails(
    LoadSpaceDetails event,
    Emitter<SpaceDetailsState> emit,
  ) async {
    emit(SpaceDetailsLoading());
    try {
      final spaceDetails = await _spaceDetailsService.getSpaceDetails(
        event.param,
      );
      emit(SpaceDetailsLoaded(spaceDetails));
    } on APIException catch (e) {
      emit(SpaceDetailsFailure(e.message));
    } catch (e) {
      emit(SpaceDetailsFailure(e.toString()));
    }
  }
}
