import 'dart:async';

import 'package:bloc/bloc.dart';
import 'package:equatable/equatable.dart';
import 'package:flutter/material.dart';
import 'package:meta/meta.dart';
import 'package:zhiying_base_widget/pages/favorites_page/bloc/favorites_repository.dart';
import 'package:zhiying_base_widget/pages/favorites_page/model/favorites_style_model.dart';
import 'package:zhiying_comm/util/empty_util.dart';

part 'favorites_event.dart';

part 'favorites_state.dart';

class FavoritesBloc extends Bloc<FavoritesEvent, FavoritesState> {
  // FavoritesBloc() : super(FavoritesInitial());

  FavoritesRepository repository;

  FavoritesBloc(this.repository);

  @override
  // TODO: implement initialState
  FavoritesState get initialState => FavoritesInitial();

  @override
  Stream<FavoritesState> mapEventToState(
    FavoritesEvent event,
  ) async* {
    /// 初始化
    if (event is FavoritesInitEvent) {
      yield* _mapInitEventToState(event);
    }
  }

  /// 初始化
  Stream<FavoritesState> _mapInitEventToState(FavoritesInitEvent event) async* {
    var cache = await repository.fetchCachedStyle(event?.model);
    if (!EmptyUtil.isEmpty(cache)) {
      yield FavoritesLoadedState(model: cache);
    }
    var result = await repository.fetchNetStyle(event?.model);
    if (!EmptyUtil.isEmpty(result)) {
      yield FavoritesLoadedState(model: result);
    } else {
      yield FavoritesErrorState();
    }
  }
}
