Skip to content
Permalink
Branch: master
Find file Copy path
Find file Copy path
Fetching contributors…
Cannot retrieve contributors at this time
106 lines (88 sloc) 3.2 KB
package com.github.johnnysc.tutor.presentation.add
import android.os.Bundle
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import com.github.johnnysc.tutor.data.Repository
import java.io.Serializable
const val SAVED_STATE = "saved AddNewPairViewModelState"
/**
* @author Asatryan on 17.06.19
*/
class AddNewPairViewModel : ViewModel() {
var stateLiveData = MutableLiveData<State>()
private var state = State(existingCategoriesEmpty = getExistingCategories().isEmpty())
fun saveNewPair() {
state.invalidData = isInvalidData()
if (state.invalidData) {
stateLiveData.value = state
state.invalidData = false
} else {
state.alreadyExists = Repository.alreadyExists(state)
if (state.alreadyExists) {
stateLiveData.value = state
} else {
Repository.saveNewData(state)
state.successfullySaved = true
stateLiveData.value = state
Repository.saveLearningPairToEdit(null)
}
}
}
fun init(savedInstanceState: Bundle?) {
if (savedInstanceState != null) {
state = savedInstanceState.getSerializable(SAVED_STATE) as State
} else {
Repository.getLearningPairToEdit()?.let {
state = State(
true,
it.categoryName,
it.categoryName,
false,
it.source,
it.translation
)
}
}
stateLiveData.value = state
}
fun saveState(outState: Bundle) = outState.putSerializable(SAVED_STATE, state)
fun getExistingCategories(): Array<String> = Repository.getCategoryNames()
fun updateSource(newSource: String) {
state.source = newSource.trim()
}
fun updateTranslation(newTranslation: String) {
state.translation = newTranslation.trim()
}
fun updateIsNewCategory(isNewCategory: Boolean) {
state.newCategory = isNewCategory
stateLiveData.value = state
}
fun updateNewCategoryName(newCategoryName: String) {
state.newCategoryName = newCategoryName.trim()
}
fun updateExistingCategoryName(position: Int) {
state.existingCategoryName = getExistingCategories()[position]
}
private fun isInvalidData() = ((state.newCategory && state.newCategoryName.isEmpty())
|| state.source.isEmpty() || state.translation.isEmpty())
fun replaceExistingPair() {
Repository.replaceExistingPair(state)
state.successfullySaved = true
stateLiveData.value = state
Repository.saveLearningPairToEdit(null)
}
fun clearExistingFlag() {
state.alreadyExists = false
}
data class State(
var newCategory: Boolean = true,
var newCategoryName: String = "",
var existingCategoryName: String = "",
var existingCategoriesEmpty: Boolean = true,
var source: String = "",
var translation: String = "",
var invalidData: Boolean = false,
var alreadyExists: Boolean = false,
var successfullySaved: Boolean = false
) : Serializable
}
You can’t perform that action at this time.