import 'package:bloc/bloc.dart';
import 'package:equatable/equatable.dart';
import 'package:syncrow_web/pages/space_management_v2/modules/communities/domain/models/community_model.dart';
import 'package:syncrow_web/pages/space_management_v2/modules/update_community/domain/params/update_community_param.dart';
import 'package:syncrow_web/pages/space_management_v2/modules/update_community/domain/services/update_community_service.dart';
import 'package:syncrow_web/services/api/api_exception.dart';

part 'update_community_event.dart';
part 'update_community_state.dart';

class UpdateCommunityBloc extends Bloc<UpdateCommunityEvent, UpdateCommunityState> {
  final UpdateCommunityService _updateCommunityService;

  UpdateCommunityBloc(
    this._updateCommunityService,
  ) : super(UpdateCommunityInitial()) {
    on<UpdateCommunity>(_onUpdateCommunity);
  }

  Future<void> _onUpdateCommunity(
    UpdateCommunity event,
    Emitter<UpdateCommunityState> emit,
  ) async {
    emit(UpdateCommunityLoading());
    try {
      final updatedCommunity = await _updateCommunityService.updateCommunity(
        event.param,
      );
      emit(UpdateCommunitySuccess(updatedCommunity));
    } on APIException catch (e) {
      emit(UpdateCommunityFailure(e.message));
    } catch (e) {
      emit(UpdateCommunityFailure(e.toString()));
    }
  }
}
