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_page/item/bloc/search_item_repostitory.dart';
import 'package:zhiying_comm/util/empty_util.dart';

part 'search_item_page_event.dart';

part 'search_item_page_state.dart';

class SearchItemPageBloc extends Bloc<SearchItemPageEvent, SearchItemPageState> {
  // SearchItemPageBloc() : super(SearchItemPageInitial());

  SearchItemRepository repository;

  SearchItemPageBloc({@required this.repository});

  @override
  // TODO: implement initialState
  SearchItemPageState get initialState => SearchItemPageInitial();

  @override
  Stream<SearchItemPageState> mapEventToState(
    SearchItemPageEvent event,
  ) async* {
    /// 初始化
    if (event is SearchItemPageInitEvent) {
      yield* _mapInitEventToState(event);
    }
  }

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