import 'package:bloc/bloc.dart';
import 'package:equatable/equatable.dart';
import 'package:flutter/cupertino.dart';import '../model/login_model.dart';


import '../request/login_request.dart';
part 'login_event.dart';
part 'login_state.dart';

class LoginBloc extends Bloc<LoginEvent, LoginState> {
  LoginBloc() : super(const LoginInitial()) {
    on<RequestLogin>((event, emit) async {
      await _requestLogin(event, emit);
    });
  }

  Future<void> _requestLogin(
      RequestLogin event, Emitter<LoginState> emit) async {
    if (event.username.isEmpty || event.password.isEmpty) {
      emit(LoginAccountRequired(event.username, event.password));
      emit(const LoginResetState());
      return;
    }
    emit(const LoginLoading());
    emit(const LoginResetState());
    RemoteService remoteService = RemoteService();
    try {
      LoginModel? loginModel = await remoteService.getLoginModel(
          context: event.context,
          username: event.username,
          password: event.password);
          emit(LoginSuccess(loginModel!));
    } catch (e) {
      emit(const LoginFailed('request false!'));
    }
  }

  @override
  Future<void> close() {
    return super.close();
  }

}

