import 'dart:async';

import 'package:boilerplate/domain/entities/product/product_favorite_data.dart';
import 'package:boilerplate/domain/usecases/product/get_product_favorites_use_case.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:injectable/injectable.dart';

part 'favorites_event.dart';
part 'favorites_state.dart';

@injectable
class FavoritesBloc extends Bloc<FavoritesEvent, FavoritesState> {
  final GetProductFavoritesUseCase _getProductFavoritesUseCase;

  FavoritesBloc(this._getProductFavoritesUseCase)
      : super(InitialState(FavoritesStateData())) {
    on<GetFavoritesEvent>(_onGetFavorites);
    on<SelectFavoriteEvent>(_onSelectFavorite);
  }

  Future<FutureOr<void>> _onGetFavorites(
    GetFavoritesEvent event,
    Emitter<FavoritesState> emit,
  ) async {
    final result = await _getProductFavoritesUseCase.execute();

    result.fold((data) {
      emit(GetFavoritesSuccessState(state.data.copyWith(
        newFavs: data,
      )));
    }, (fail) {
      emit(GetFavoritesFailState(state.data));
    });
  }

  FutureOr<void> _onSelectFavorite(
    SelectFavoriteEvent event,
    Emitter<FavoritesState> emit,
  ) {
    emit(SelectedFavoriteState(state.data, event.productId));
  }
}
