import 'dart:async';

import 'package:bloc/bloc.dart';
import 'package:flutter/cupertino.dart';
import 'package:zhiying_base_widget/widgets/home/home_slide_banner/bloc/home_slide_banner_event.dart';
import 'package:zhiying_base_widget/widgets/home/home_slide_banner/bloc/home_slide_banner_repository.dart';
import 'package:zhiying_base_widget/widgets/home/home_slide_banner/bloc/home_slide_banner_state.dart';
import 'package:zhiying_comm/util/empty_util.dart';

import './bloc.dart';

class HomeSlideBannerBloc extends Bloc<HomeSlideBannerEvent, HomeSlideBannerState> {
  HomeSlideBannerRepository repository;

  HomeSlideBannerBloc({@required this.repository});

  @override
  HomeSlideBannerState get initialState => InitialHomeSlideBannerState();

  @override
  Stream<HomeSlideBannerState> mapEventToState(HomeSlideBannerEvent event) async* {
    final currentState = state;

    /// 初始化
    if (event is HomeBannerInitEvent) {
      print('---------HomeBannerInitEvent---------');
      yield* _mapInitEventToState(event);
    }
  }

  /// 初始化
  Stream<HomeSlideBannerState> _mapInitEventToState(HomeBannerInitEvent event) async* {
    var parent = await repository.fetchPreantData(event.model);
    if(!EmptyUtil.isEmpty(parent)){
      yield HomeSlideBannerLoadedState(datas: parent);
      return;
    }
    var cached = await repository.fetchCachedDate(id: event.model['mod_id']);
    if (!EmptyUtil.isEmpty(cached)) yield HomeSlideBannerCachedState(datas: cached);
    var param = await repository.fetchData(id: event.model['mod_id']);
    if (!EmptyUtil.isEmpty(param))
      yield HomeSlideBannerLoadedState(datas: param);
    else
      yield HomeSlideBannerLoadError();
  }
}
