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/create_community/domain/param/create_community_param.dart';
import 'package:syncrow_web/pages/space_management_v2/modules/create_community/domain/services/create_community_service.dart';
import 'package:syncrow_web/services/api/api_exception.dart';

part 'create_community_event.dart';
part 'create_community_state.dart';

class CreateCommunityBloc extends Bloc<CreateCommunityEvent, CreateCommunityState> {
  final CreateCommunityService _createCommunityService;

  CreateCommunityBloc(
    this._createCommunityService,
  ) : super(CreateCommunityInitial()) {
    on<CreateCommunity>(_onCreateCommunity);
  }

  Future<void> _onCreateCommunity(
    CreateCommunity event,
    Emitter<CreateCommunityState> emit,
  ) async {
    emit(CreateCommunityLoading());
    try {
      final createdCommunity = await _createCommunityService.createCommunity(
        event.param,
      );
      emit(CreateCommunitySuccess(createdCommunity));
    } on APIException catch (e) {
      emit(CreateCommunityFailure(e.message));
    } catch (e) {
      emit(CreateCommunityFailure(e.toString()));
    }
  }
}
