import 'dart:async';

import 'package:bloc/bloc.dart';
import 'package:equatable/equatable.dart';
import 'package:flutter/cupertino.dart';
import 'search_repository.dart';
import 'package:zhiying_comm/zhiying_comm.dart';

part 'search_event.dart';

part 'search_state.dart';

class SearchBloc extends Bloc<SearchEvent, SearchState> {
  // SreachBloc() : super(SreachInitial());

  SearchRepository repository;

  SearchBloc({this.repository});

  @override
  SearchState get initialState => SearchInitial();

  @override
  Stream<SearchState> mapEventToState(
    SearchEvent event,
  ) async* {
    /// 初始化方法
    if (event is SearchInitEvent) {
      yield* _mapInitEventToState(event);
    }

    /// 搜索的方法
    if (event is SearchSubmitEvent) {
      yield* _mapSearchSubmitToState(event);
    }
  }

  /// 初始化
  Stream<SearchState> _mapInitEventToState(SearchInitEvent event) async* {
    /// 获取缓存的数据
    var cache = await repository.fetchCachedData(event.model);
    if(!EmptyUtil.isEmpty(cache)){
      print('缓存数据');
      yield SearchLoadedState(model: cache);
    }
    /// 获取数据
    var result = await repository.fetchInit(event.model);
    Logger.log('result = ${result.toString()}');
    if (!EmptyUtil.isEmpty(result)) {
      yield SearchLoadedState(model: result);
    } else {
      yield SearchErrorState();
    }
  }

  /// 搜索的方法
  Stream<SearchState> _mapSearchSubmitToState(SearchSubmitEvent event) async* {
    var result = await repository.fetchSearchSubmit(event.model);
  }
}
