import 'package:equatable/equatable.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import '../../repositories/forgot_password_repository.dart';

part 'forgot_password_event.dart';
part 'forgot_password_state.dart';

class ForgotPasswordBloc extends Bloc<ForgotPasswordEvent, ForgotPasswordState> {
  final ForgotPasswordRepository _forgotPasswordRepository;

  ForgotPasswordBloc({ForgotPasswordRepository? forgotPasswordRepository})
      : _forgotPasswordRepository = forgotPasswordRepository ?? ForgotPasswordRepository(),
        super(const ForgotPasswordState()) {
    on<ForgotPasswordSubmitted>(_onForgotPasswordSubmitted);
    on<ForgotPasswordEmailErrorToggled>(_onEmailErrorToggled);
    on<ForgotPasswordReset>(_onReset);
  }

  Future<void> _onForgotPasswordSubmitted(
      ForgotPasswordSubmitted event,
      Emitter<ForgotPasswordState> emit,
      ) async {
    emit(state.copyWith(status: ForgotPasswordStatus.loading, errorMessage: null));

    try {
      await _forgotPasswordRepository.forgotPassword(
        emailAddress: event.emailAddress,
      );

      emit(state.copyWith(status: ForgotPasswordStatus.success));
    } catch (e) {
      emit(state.copyWith(
        status: ForgotPasswordStatus.failure,
        errorMessage: e.toString().replaceAll('Exception: ', ''),
      ));
    }
  }

  void _onEmailErrorToggled(
      ForgotPasswordEmailErrorToggled event,
      Emitter<ForgotPasswordState> emit,
      ) {
    emit(state.copyWith(showEmailError: event.show));
  }

  Future<void> _onReset(
      ForgotPasswordReset event,
      Emitter<ForgotPasswordState> emit,
      ) async {
    emit(const ForgotPasswordState());
  }
}