Files
syncrow-web/lib/pages/space_tree/bloc/space_tree_bloc.dart
2025-01-04 17:45:15 +03:00

70 lines
2.5 KiB
Dart

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<SpaceTreeEvent, SpaceTreeState> {
String selectedCommunityId = '';
String selectedSpaceId = '';
SpaceTreeBloc() : super(const SpaceTreeState()) {
on<InitialEvent>(_fetchSpaces);
on<OnSelectSpaceEvent>(_onSelectSpace);
}
_fetchSpaces(InitialEvent event, Emitter<SpaceTreeState> emit) async {
emit(SpaceTreeLoadingState());
try {
// _onloadProducts();
List<CommunityModel> communities = await CommunitySpaceManagementApi().fetchCommunities();
List<CommunityModel> updatedCommunities = await Future.wait(
communities.map((community) async {
List<SpaceModel> 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<SpaceTreeState> 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'));
}
}
}