import 'package:driverapp/config/shared_pref_kay.dart';
import 'package:driverapp/core/enum/viewstate.dart';
import 'package:driverapp/core/model/authentication/login_request.dart';
import 'package:driverapp/core/service/authentication_service.dart';
import 'package:driverapp/core/service/client/base_app_client.dart';
import 'package:driverapp/core/viewModels/base_view_model.dart';

import '../../locator.dart';

enum APP_STATUS { LOADING, UNAUTHENTICATED, AUTHENTICATED }

class AuthenticationViewModel extends BaseViewModel {
  AuthenticationService _authenticationService = locator<AuthenticationService>();

  APP_STATUS get status {
    if (state == ViewState.Busy || state == ViewState.BusyLocal) {
      return APP_STATUS.LOADING;
    } else {
      if (  user != null) {
        return APP_STATUS.AUTHENTICATED;
      } else {
        return APP_STATUS.UNAUTHENTICATED;
      }
    }
  }

  login(LoginRequest loginRequest) async {
    setState(ViewState.BusyLocal);
    await _authenticationService.login(loginRequest);
    if (_authenticationService.hasError) {
      error = _authenticationService.error;
      setState(ViewState.ErrorLocal);
    } else {
      sharedPref.setObject(
          USER_PROFILE, _authenticationService.authenticatedUser);
      sharedPref.setString(TOKEN, _authenticationService.token);
      setState(ViewState.Idle);
    }
  }
}
