import 'dart:async';

import 'package:bloc/bloc.dart';
import 'package:equatable/equatable.dart';
import 'package:flutter/cupertino.dart';
import 'package:zhiying_base_widget/pages/search_result_page/item/bloc/search_result_item_repository.dart';
import 'package:zhiying_comm/zhiying_comm.dart';

part 'search_result_item_event.dart';

part 'search_result_item_state.dart';

class SearchResultItemBloc extends Bloc<SearchResultItemEvent, SearchResultItemState> {
  // SearchResultItemBloc() : super(SearchResultItemInitial());

  SearchResultItemRepository repository;

  @override
  SearchResultItemState get initialState => SearchResultItemInitial();

  SearchResultItemBloc({@required this.repository});

  @override
  Stream<SearchResultItemState> mapEventToState(
    SearchResultItemEvent event,
  ) async* {
    if (event is SearchResultItemInitEvent) {
      yield* _mapInitEventToState(event);
    }
  }

  /// 初始化
  Stream<SearchResultItemState> _mapInitEventToState(SearchResultItemInitEvent event) async* {
    /// 获取缓存数据
    var cache = await repository.fetchCacheData(event.model);
    if (!EmptyUtil.isEmpty(cache)) {
      yield SearchResultItemLoadedState(model: cache);
    }

    /// 访问网络数据
    var result = await repository.fetchInitData(event.model);
    if (!EmptyUtil.isEmpty(result)) {
      yield SearchResultItemLoadedState(model: result);
    } else {
      yield SearchResultItemErrorState();
    }
  }
}
