import 'dart:async';

import 'package:bloc/bloc.dart';
import 'package:flutter/cupertino.dart';
import 'package:zhiying_base_widget/widgets/home/home_quick_entry/bloc/home_quick_entry_repository.dart';
import 'package:zhiying_comm/util/empty_util.dart';

import './bloc.dart';

class HomeQuickEntryBloc
    extends Bloc<HomeQuickEntryEvent, HomeQuickEntryState> {
  HomeQuickEntryRepository repository;

  HomeQuickEntryBloc({@required this.repository});

  @override
  HomeQuickEntryState get initialState => InitialHomeQuickEntryState();

  @override
  Stream<HomeQuickEntryState> mapEventToState(
      HomeQuickEntryEvent event) async* {
    final currentState = state;
    if (event is HomeQuickEntryInitEvent) {
      yield* _mapHomeQuickEntryInitToState(event);
    }
  }

  /// 初始化
  Stream<HomeQuickEntryState> _mapHomeQuickEntryInitToState(
      HomeQuickEntryInitEvent event) async* {
    /// 获取缓存数据
    var cached = await repository.fetchCachedData();
    if (!EmptyUtil.isEmpty(cached)) {
      yield HomeQuickEntryCachedState();
    }
    var result = await repository.fetchData();
    if (!EmptyUtil.isEmpty(result)) {
      yield HomeQuickEntryLoadedState();
    } else {
      yield HomeQuickEntryErrorState();
    }
  }
}
