import 'dart:async';

import 'package:bloc/bloc.dart';
import 'package:zhiying_comm/pages/empty_page/bloc/empty_page_repository.dart';
import 'package:zhiying_comm/util/empty_util.dart';
import 'empty_page_state.dart';
import 'empty_page_event.dart';

class EmptyPageBloc extends Bloc<EmptyPageEvent, EmptyPageState> {
  @override
  EmptyPageState get initialState => EmptyPageInitial();

  EmptyPageRepository repository;

  EmptyPageBloc(this.repository);

  @override
  Stream<EmptyPageState> mapEventToState(
    EmptyPageEvent event,
  ) async* {
    if (event is EmptyPageInitEvent) {
      yield* _mapInitEventToState(event);
    }
  }

  /// 初始化
  Stream<EmptyPageState> _mapInitEventToState(EmptyPageInitEvent event) async* {
    var cache = await repository.fetchCacheData();
    if (!EmptyUtil.isEmpty(cache)) {
      yield EmptyPageLoadedState(model: cache);
    }
    var result = await repository.fetchNetData();
    if (!EmptyUtil.isEmpty(result)) {
      yield EmptyPageLoadedState(model: result);
    } else {
      yield EmptyPageErrorState();
    }
  }
}
