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 cache = await repository.fetchCacheData(modId: event.model['mod_id']);
    if (!EmptyUtil.isEmpty(cache)) yield HomeBannerCacheState();
    var result = await repository.fetchNetData(modId: event.model['mod_id']);
    if (!EmptyUtil.isEmpty(result))
      yield HomeBannerLoadedState();
    else
      yield HomeBannerErrorState();
  }
}
