import 'package:bloc/bloc.dart';
import 'package:telnow_mobile_new/src/api/api_auth_repository.dart';
import 'package:telnow_mobile_new/src/injector/injector.dart';
import 'package:telnow_mobile_new/src/model/login/login_body.dart';
import 'package:telnow_mobile_new/src/model/token/token.dart';
import 'package:telnow_mobile_new/src/storage/sharedpreferences/shared_preferences_manager.dart';

abstract class LoginState {}

class LoginInitial extends LoginState {}

class LoginLoading extends LoginState {}

class LoginFailure extends LoginState {
  final String error;

  LoginFailure(this.error);
}

class LoginSuccess extends LoginState {
}

class LoginEvent extends LoginState {
  final LoginBody loginBody;

  LoginEvent(this.loginBody);
}

class LoginBloc extends Bloc<LoginEvent, LoginState> {
  final ApiAuthRepository apiAuthRepository = ApiAuthRepository();
  final SharedPreferencesManager sharedPreferencesManager = locator<SharedPreferencesManager>();

  LoginBloc(super.initialState);

  // @override
  Stream<LoginState> mapEventToState(LoginEvent event) async* {
    LoginBody loginBody = event.loginBody;
    if (loginBody.username.isEmpty) {
      yield LoginFailure('username');
      return;
    }
    else if (loginBody.password.isEmpty) {
      yield LoginFailure('password');
      return;
    }
    yield LoginLoading();
    Token token = await apiAuthRepository.postLoginUser(loginBody);
    if (token.error != null) {
      yield LoginFailure(token.error!);
      return;
    }
    await sharedPreferencesManager.putString(SharedPreferencesManager.keyAccessToken, token.accessToken!);
    await sharedPreferencesManager.putString(SharedPreferencesManager.keyRefreshToken, token.refreshToken!);
    await sharedPreferencesManager.putBool(SharedPreferencesManager.keyIsLogin, true);
    await sharedPreferencesManager.putString(SharedPreferencesManager.keyScoope, 'INSIDE');
    await sharedPreferencesManager.putInt(SharedPreferencesManager.keyCountRefreshToken, 0);
    yield LoginSuccess();
  }

}