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/bloc/search_result_repository.dart';
import 'package:zhiying_comm/zhiying_comm.dart';

part 'search_result_event.dart';

part 'search_result_state.dart';

class SearchResultBloc extends Bloc<SearchResultEvent, SearchResultState> {
  // SearchResultBloc() : super(SearchResultInitial());

  SearchResultRepository repository;

  SearchResultBloc({@required this.repository});

  @override
  SearchResultState get initialState => SearchResultInitial();

  @override
  Stream<SearchResultState> mapEventToState(
    SearchResultEvent event,
  ) async* {
    if (event is SearchResultInitEvent) {
      yield* _mapInitEventToState(event);
    }
  }

  /// 初始化
  Stream<SearchResultState> _mapInitEventToState(SearchResultInitEvent event) async* {
    var cache = await repository.fetchCachedData(event.model);
    if(!EmptyUtil.isEmpty(cache)){
      yield SearchResultLoadedState(model: cache);
    }
    var result = await repository.fetchInit(event.model);
    if(!EmptyUtil.isEmpty(result)){
      yield SearchResultLoadedState(model: result);
    }else{
      yield SearchResultErrorState();
    }

  }
}
