import 'dart:async';

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

import './bloc.dart';

class HomeBannerBloc extends Bloc<HomeBannerEvent, HomeBannerState> {
  HomeBannerRepository repository;

  HomeBannerBloc({@required this.repository});

  @override
  HomeBannerState get initialState => InitialHomeBannerState();

  @override
  Stream<HomeBannerState> mapEventToState(
    HomeBannerEvent event,
  ) async* {
    final currentState = state;
    if (event is HomeBannerInitEvent) {
      yield* _mapHomeBannerInitEventToState(event);
    }
  }

  /// 初始化
  Stream<HomeBannerState> _mapHomeBannerInitEventToState(HomeBannerInitEvent event) async* {
    var parentData = await repository.fetchParentData(model: event.model);
    if(!EmptyUtil.isEmpty(parentData)){
      yield HomeBannerLoadedState(model: parentData);
      return;
    }
    var cache = await repository.fetchCacheData(model: event.model);
    if (!EmptyUtil.isEmpty(cache)) yield HomeBannerCacheState(model: cache);
    var result = await repository.fetchNetData(model: event.model);
    if (!EmptyUtil.isEmpty(result))
      yield HomeBannerLoadedState(model: result);
    else
      yield HomeBannerErrorState();
  }
}
