import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:syncrow_web/pages/space_tree/bloc/space_tree_event.dart'; import 'package:syncrow_web/pages/space_tree/bloc/space_tree_state.dart'; import 'package:syncrow_web/pages/spaces_management/all_spaces/model/community_model.dart'; import 'package:syncrow_web/pages/spaces_management/all_spaces/model/space_model.dart'; import 'package:syncrow_web/services/space_mana_api.dart'; class SpaceTreeBloc extends Bloc { String selectedCommunityId = ''; String selectedSpaceId = ''; SpaceTreeBloc() : super(const SpaceTreeState()) { on(_fetchSpaces); on(_onSelectSpace); } _fetchSpaces(InitialEvent event, Emitter emit) async { emit(SpaceTreeLoadingState()); try { // _onloadProducts(); List communities = await CommunitySpaceManagementApi().fetchCommunities(); List updatedCommunities = await Future.wait( communities.map((community) async { List spaces = await CommunitySpaceManagementApi().getSpaceHierarchy(community.uuid); return CommunityModel( uuid: community.uuid, createdAt: community.createdAt, updatedAt: community.updatedAt, name: community.name, description: community.description, spaces: spaces, region: community.region, ); }).toList(), ); if (updatedCommunities.isNotEmpty && state.selectedSpace.isEmpty && state.selectedCommunity.isEmpty) { selectedCommunityId = updatedCommunities[0].uuid; } else { selectedCommunityId = state.selectedCommunity; selectedSpaceId = state.selectedSpace; } emit(state.copyWith( communitiesList: updatedCommunities, selectedCommunity: selectedCommunityId, selectedSpace: selectedSpaceId)); } catch (e) { emit(SpaceTreeErrorState('Error loading communities and spaces: $e')); } } _onSelectSpace(OnSelectSpaceEvent event, Emitter emit) async { try { selectedCommunityId = event.communityId; selectedSpaceId = event.spaceId; emit(state.copyWith( communitiesList: state.spacesList, selectedCommunity: event.communityId, selectedSpace: event.spaceId)); } catch (e) { emit(const SpaceTreeErrorState('Something went wrong')); } } }