Files
syncrow-web/lib/pages/spaces_management/bloc/space_management_bloc.dart
2024-10-09 11:04:56 +04:00

95 lines
3.1 KiB
Dart

import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:syncrow_web/pages/spaces_management/model/community_model.dart';
import 'package:syncrow_web/pages/spaces_management/model/space_model.dart';
import 'package:syncrow_web/pages/spaces_management/bloc/space_management_event.dart';
import 'package:syncrow_web/pages/spaces_management/bloc/space_management_state.dart';
import 'package:syncrow_web/services/space_mana_api.dart';
class SpaceManagementBloc
extends Bloc<SpaceManagementEvent, SpaceManagementState> {
final CommunitySpaceManagementApi _api;
SpaceManagementBloc(this._api) : super(SpaceManagementInitial()) {
on<LoadCommunityAndSpacesEvent>(_onLoadCommunityAndSpaces);
on<CreateSpaceEvent>(_onCreateSpace);
on<UpdateSpacePositionEvent>(_onUpdateSpacePosition);
}
void _onLoadCommunityAndSpaces(
LoadCommunityAndSpacesEvent event,
Emitter<SpaceManagementState> emit,
) async {
emit(SpaceManagementLoading());
try {
// Fetch all communities
List<CommunityModel> communities = await _api.fetchCommunities();
// Use Future.wait to handle async calls within map
List<CommunityModel> updatedCommunities = await Future.wait(
communities.map((community) async {
List<SpaceModel> spaces =
await _api.getSpaceHierarchy(community.uuid);
debugPrint(
'Fetched spaces for community ${community.name}: ${spaces.length}');
return CommunityModel(
uuid: community.uuid,
createdAt: community.createdAt,
updatedAt: community.updatedAt,
name: community.name,
description: community.description,
spaces: spaces, // New spaces list
region: community.region,
);
}).toList(),
);
emit(SpaceManagementLoaded(communities: updatedCommunities));
} catch (e) {
emit(SpaceManagementError('Error loading communities and spaces: $e'));
}
}
void _onCreateSpace(
CreateSpaceEvent event,
Emitter<SpaceManagementState> emit,
) {
// Handle space creation logic
// You can emit a new state here based on your needs
emit(SpaceCreationSuccess());
}
void _onUpdateSpacePosition(
UpdateSpacePositionEvent event,
Emitter<SpaceManagementState> emit,
) {
// Handle space position update logic
}
void _onCreateCommunity(
CreateCommunityEvent event,
Emitter<SpaceManagementState> emit,
) async {
try {
CommunityModel? community = await _api.createCommunity(
event.name,
event.description,
event.regionId,
);
if (community != null) {
List<CommunityModel> updatedCommunities = List.from((state as SpaceManagementLoaded).communities)
..add(community); // Add the newly created community to the list
emit(SpaceManagementLoaded(communities: updatedCommunities));
} else {
emit(const SpaceManagementError('Error creating community'));
}
} catch (e) {
emit(SpaceManagementError('Error creating community: $e'));
}
}
}