import 'dart:async';

import 'package:aitrainer_app/repository/user_repository.dart';
import 'package:aitrainer_app/util/common.dart';
import 'package:bloc/bloc.dart';
import 'package:equatable/equatable.dart';

part 'password_reset_event.dart';
part 'password_reset_state.dart';

class PasswordResetBloc extends Bloc<PasswordResetEvent, PasswordResetState> {
  final UserRepository userRepository;
  PasswordResetBloc({required this.userRepository}) : super(PasswordResetInitial());

  @override
  Stream<PasswordResetState> mapEventToState(
    PasswordResetEvent event,
  ) async* {
    try {
      if (event is PasswordResetEmailChange) {
        yield PasswordResetLoading();
        final String email = event.email;
        userRepository.setEmail(email);
        yield PasswordResetReady();
      } else if (event is PasswordResetSubmit) {
        yield PasswordResetLoading();
        await userRepository.resetPassword();
        yield PasswordResetFinished();
      }
    } on Exception catch (e) {
      yield PasswordResetError(message: e.toString());
    }
  }

  String? emailValidation(String email) {
    String? message = Common.emailValidation(email);

    return message;
  }
}
