ariane/app/src/main/java/oppen/tva/ui/GemViewModel.kt

64 lines
1.7 KiB
Kotlin

package oppen.tva.ui
import androidx.lifecycle.ViewModel
import oppen.tva.Gem
import oppen.tva.io.gemini.Datasource
import oppen.tva.io.GemState
import oppen.tva.io.bookmarks.BookmarksDatasource
import java.net.URI
class GemViewModel: ViewModel() {
private lateinit var gemini: Datasource
private lateinit var bookmarks: BookmarksDatasource
private var onState: (state: GemState) -> Unit = {}
private val history = mutableListOf<URI>()
fun initialise(gemini: Datasource, bookmarks: BookmarksDatasource, onState: (state: GemState) -> Unit){
this.gemini = gemini
this.bookmarks = bookmarks
this.onState = onState
request(URI.create(Gem.DEFAULT_HOME_CAPSULE))//todo - regression: should check prefs...
onState(GemState.TabChange(1))
}
fun request(address: String) {
request(URI.create(address))
}
fun request(uri: URI){
gemini.request(uri){ state ->
if(history.isEmpty()){
history.add(uri)
}else if(history.last().toString() != uri.toString()) {
history.add(uri)
}
onState(state)
}
}
fun canGoBack(): Boolean = history.size > 1
@ExperimentalStdlibApi
fun goBack(){
when {
history.size >= 2 -> {
logHistory()
val previous = history[history.size - 2]
history.removeLast()
println("Requesting history item: $previous")
request(previous)
logHistory()
}
}
}
private fun logHistory(){
history.forEach { uri ->
println("History: $uri")
}
}
}