import 'dart:async';
import 'package:bloc/bloc.dart';
import './bloc.dart';
import 'login_repository.dart';
import 'package:zhiying_comm/util/empty_util.dart';

class LoginBloc extends Bloc<LoginEvent, LoginState> {
  LoginRepository repository;

  LoginBloc({this.repository});

  @override
  LoginState get initialState => InitialLoginState();

  @override
  Stream<LoginState> mapEventToState(
    LoginEvent event,
  ) async* {
    // TODO: Add Logic
    final currentState = state;

    /// 初始化
    if (event is LoginInitEvent) {
      yield* _mapLoginInitEventToState(event);
    }
  }

  /// 获取页面数据
  Stream<LoginState> _mapLoginInitEventToState(LoginInitEvent event) async* {
    var cache = await repository.fetchCachePageData();
    if (!EmptyUtil.isEmpty(cache)) yield LoginCacheState( model: cache);
    var result = await repository.fetchNetPageData();
    if (!EmptyUtil.isEmpty(result))
      yield LoginLoadedState(model: result);
    else
      yield LoginErrorState();
  }
}
