import 'package:bloc/bloc.dart';
import 'package:dartz/dartz.dart';
import 'package:freezed_annotation/freezed_annotation.dart';
import 'package:injectable/injectable.dart';

import '../../../domain/game/game.dart';

part 'game_prize_loader_event.dart';
part 'game_prize_loader_state.dart';
part 'game_prize_loader_bloc.freezed.dart';

@injectable
class GamePrizeLoaderBloc
    extends Bloc<GamePrizeLoaderEvent, GamePrizeLoaderState> {
  final IGameRepository _repository;
  GamePrizeLoaderBloc(this._repository)
    : super(GamePrizeLoaderState.initial()) {
    on<GamePrizeLoaderEvent>(_onGamePrizeLoaderEvent);
  }

  Future<void> _onGamePrizeLoaderEvent(
    GamePrizeLoaderEvent event,
    Emitter<GamePrizeLoaderState> emit,
  ) {
    return event.map(
      fetched: (e) async {
        emit(state.copyWith(isFetching: true, failureOptionGamePrize: none()));

        final result = await _repository.gamePrizeByGameId(id: e.id);

        var data = result.fold(
          (f) => state.copyWith(failureOptionGamePrize: optionOf(f)),
          (gamePrize) => state.copyWith(gamePrize: gamePrize),
        );

        emit(data.copyWith(isFetching: false));
      },
    );
  }
}
