Commit 38842264 by Paktalin

Refactoring in saveWords method

parent 646fc562
......@@ -9,6 +9,7 @@ import com.paktalin.vocabularynotebook.firestoreitems.UserPojo
import com.paktalin.vocabularynotebook.firestoreitems.VocabularyPojo
import com.paktalin.vocabularynotebook.firestoreitems.WordPojo
import com.paktalin.vocabularynotebook.ui.activities.LogInActivity
import com.paktalin.vocabularynotebook.vocabulary.ModifiedVocabulary.Label
import java.util.*
class FirestoreManager {
......@@ -46,19 +47,14 @@ class FirestoreManager {
}
}
fun saveWords(wordMap: MutableMap<WordPojo, Boolean>) {
if (wordMap.isEmpty())
return
fun saveWords(wordMap: MutableMap<Label, MutableList<WordPojo>>) {
if (wordMap.isEmpty()) return
val batch = db.batch()
wordMap.forEach {
entry -> run {
if (entry.value) batch.delete(wordsCollection.document(entry.key.id!!))
else batch.set(wordsCollection.document(entry.key.id!!), entry.key)
}}
wordMap.clear()
batch.commit().addOnCompleteListener { Log.d(TAG, "words are successfully pushed to Firestore") }
wordMap[Label.DELETED]?.forEach { w -> batch.delete(wordsCollection.document(w.id!!)) }
wordMap[Label.EDITED]?.forEach { w -> batch.set(wordsCollection.document(w.id!!), w) }
wordMap[Label.DELETED]?.clear()
wordMap[Label.EDITED]?.clear()
batch.commit()
}
fun extractVocabulary(onComplete: (querySnapshot: QuerySnapshot?) -> Unit) {
......
......@@ -4,30 +4,39 @@ import com.paktalin.vocabularynotebook.firestoreitems.WordPojo
import com.paktalin.vocabularynotebook.utils.FirestoreManager
class ModifiedVocabulary : Vocabulary {
var wordMap = mutableMapOf<WordPojo, Boolean>()
var wordMap = mutableMapOf(
Pair(Label.DELETED, mutableListOf<WordPojo>()),
Pair(Label.EDITED, mutableListOf()))
private val maxPermitted = 9
private var currentSize = 0
override fun addWord(newWord: WordPojo) {
add(newWord, false)
add(newWord, Label.EDITED)
}
override fun updateWord(updatedWord: WordPojo) {
add(updatedWord, false)
add(updatedWord, Label.EDITED)
}
override fun deleteWord(wordPojo: WordPojo) {
add(wordPojo, true)
add(wordPojo, Label.DELETED)
}
override fun addAll(words: MutableList<WordPojo>) { }
private fun add(wordPojo: WordPojo, deleted: Boolean) {
wordMap[wordPojo] = deleted
if (wordMap.size == maxPermitted)
private fun add(wordPojo: WordPojo, label: Label) {
wordMap[label]?.add(wordPojo)
currentSize++
if (currentSize > maxPermitted) {
currentSize = 0
FirestoreManager().saveWords(wordMap)
}
}
fun get(): MutableMap<WordPojo, Boolean> {
fun get(): MutableMap<Label, MutableList<WordPojo>> {
return wordMap
}
enum class Label { DELETED, EDITED }
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or sign in to comment