import 'package:bloc/bloc.dart';
import 'package:equatable/equatable.dart';
import 'package:syncrow_web/pages/space_management_v2/modules/tags/domain/models/tag.dart';
import 'package:syncrow_web/pages/space_management_v2/modules/tags/domain/params/load_tags_param.dart';
import 'package:syncrow_web/pages/space_management_v2/modules/tags/domain/services/tags_service.dart';
import 'package:syncrow_web/services/api/api_exception.dart';

part 'tags_event.dart';
part 'tags_state.dart';

class TagsBloc extends Bloc<TagsEvent, TagsState> {
  final TagsService _tagsService;

  TagsBloc(this._tagsService) : super(TagsInitial()) {
    on<LoadTags>(_onLoadTags);
  }

  Future<void> _onLoadTags(
    LoadTags event,
    Emitter<TagsState> emit,
  ) async {
    emit(TagsLoading());
    try {
      final tags = await _tagsService.loadTags(event.param);
      emit(TagsLoaded(tags));
    } on APIException catch (e) {
      emit(TagsFailure(e.message));
    } catch (e) {
      emit(TagsFailure(e.toString()));
    }
  }
}
