package mx.trackermap.TrackerMap.android.session import android.util.Log import androidx.lifecycle.MutableLiveData import androidx.lifecycle.SavedStateHandle import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import com.zhuinden.eventemitter.EventEmitter import com.zhuinden.eventemitter.EventSource import kotlinx.coroutines.launch import mx.trackermap.TrackerMap.client.apis.SessionApi class LoginViewModel( private val sessionApi: SessionApi, savedStateHandle: SavedStateHandle ) : ViewModel() { sealed class LoginState { object Loading: LoginState() object EmailMissing : LoginState() object PasswordMissing : LoginState() object Failure : LoginState() object Success : LoginState() } val email: MutableLiveData = savedStateHandle.getLiveData("user", "") val password: MutableLiveData = savedStateHandle.getLiveData("password", "") private val loginStateEmitter = EventEmitter() val loginState: EventSource = loginStateEmitter fun restoreSession() { loginStateEmitter.emit(LoginState.Loading); viewModelScope.launch { try { val user = sessionApi.sessionGet() Log.d("LoginViewModel", user.toString()) loginStateEmitter.emit(LoginState.Success) } catch (e: Exception) { Log.d("LoginViewModel", "No session") } } } fun login() { val email = email.value!!.toString().trim() val password = password.value!!.toString().trim() if (email.isEmpty()) { loginStateEmitter.emit(LoginState.EmailMissing) return } if (password.isEmpty()) { loginStateEmitter.emit(LoginState.PasswordMissing) return } loginStateEmitter.emit(LoginState.Loading) viewModelScope.launch { try { val user = sessionApi.sessionPost(email, password) Log.d("LoginViewModel", user.toString()) loginStateEmitter.emit(LoginState.Success) } catch (e: Exception) { loginStateEmitter.emit(LoginState.Failure) } } } }