import 'dart:async';

import 'package:meta/meta.dart';
import 'package:bloc/bloc.dart';
import 'package:equatable/equatable.dart';

import 'package:{{ name }}/repository/AuthenticationRepository.dart';
import 'package:{{ name }}/bloc/Authentication/AuthenticationBloc.dart';
import 'package:{{ name }}/utils/hadleError.dart';

part 'LoginEvent.dart';
part 'LoginState.dart';

class LoginBloc extends Bloc<LoginEvent, LoginState> {
  final AuthenticationRepository authenticationRepository;
  final AuthenticationBloc authenticationBloc;

  LoginBloc({
    @required this.authenticationRepository,
    @required this.authenticationBloc,
  })  : assert(authenticationRepository != null),
        assert(authenticationBloc != null);

  @override
  LoginState get initialState => LoginInitial();

  @override
  Stream<LoginState> mapEventToState(LoginEvent event) async* {
    if (event is LoginButtonPressed) {
      yield LoginLoading();

      try {
        final token = await authenticationRepository.login(
          email: event.email,
          password: event.password,
          rememberMe: event.rememberMe,
        );

        authenticationBloc.add(UserLoggedIn(token: token.accessToken));
        yield LoginSuccces();
      } catch (error) {
        yield LoginFailure(error: HandleError.getError(error));
      }
    }
  }
}