import 'package:bloc/bloc.dart'; import 'package:kiwi/kiwi.dart'; import 'package:logging/logging.dart'; import 'package:nc_photos/account.dart'; import 'package:nc_photos/bloc/bloc_util.dart' as bloc_util; import 'package:nc_photos/entity/person.dart'; import 'package:nc_photos/entity/person/data_source.dart'; abstract class ListPersonBlocEvent { const ListPersonBlocEvent(); } class ListPersonBlocQuery extends ListPersonBlocEvent { const ListPersonBlocQuery(this.account); @override toString() { return "$runtimeType {" "account: $account, " "}"; } final Account account; } abstract class ListPersonBlocState { const ListPersonBlocState(this.account, this.items); @override toString() { return "$runtimeType {" "account: $account, " "items: List {length: ${items.length}}, " "}"; } final Account? account; final List items; } class ListPersonBlocInit extends ListPersonBlocState { ListPersonBlocInit() : super(null, const []); } class ListPersonBlocLoading extends ListPersonBlocState { const ListPersonBlocLoading(Account? account, List items) : super(account, items); } class ListPersonBlocSuccess extends ListPersonBlocState { const ListPersonBlocSuccess(Account? account, List items) : super(account, items); } class ListPersonBlocFailure extends ListPersonBlocState { const ListPersonBlocFailure( Account? account, List items, this.exception) : super(account, items); @override toString() { return "$runtimeType {" "super: ${super.toString()}, " "exception: $exception, " "}"; } final dynamic exception; } /// List all people recognized in an account class ListPersonBloc extends Bloc { ListPersonBloc() : super(ListPersonBlocInit()) { on(_onEvent); } static ListPersonBloc of(Account account) { final name = bloc_util.getInstNameForAccount("ListPersonBloc", account); try { _log.fine("[of] Resolving bloc for '$name'"); return KiwiContainer().resolve(name); } catch (_) { // no created instance for this account, make a new one _log.info("[of] New bloc instance for account: $account"); final bloc = ListPersonBloc(); KiwiContainer().registerInstance(bloc, name: name); return bloc; } } Future _onEvent( ListPersonBlocEvent event, Emitter emit) async { _log.info("[_onEvent] $event"); if (event is ListPersonBlocQuery) { await _onEventQuery(event, emit); } } Future _onEventQuery( ListPersonBlocQuery ev, Emitter emit) async { try { emit(ListPersonBlocLoading(ev.account, state.items)); emit(ListPersonBlocSuccess(ev.account, await _query(ev))); } catch (e, stackTrace) { _log.severe("[_onEventQuery] Exception while request", e, stackTrace); emit(ListPersonBlocFailure(ev.account, state.items, e)); } } Future> _query(ListPersonBlocQuery ev) { const personRepo = PersonRepo(PersonRemoteDataSource()); return personRepo.list(ev.account); } static final _log = Logger("bloc.list_personListPersonBloc"); }