package mx.trackermap.TrackerMap.android.units import android.util.Log import androidx.lifecycle.MutableLiveData import androidx.lifecycle.SavedStateHandle import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import kotlinx.coroutines.DelicateCoroutinesApi import kotlinx.coroutines.flow.collect import kotlinx.coroutines.launch import mx.trackermap.TrackerMap.client.models.UnitInformation import mx.trackermap.TrackerMap.controllers.UnitsController import org.koin.core.component.KoinComponent import org.koin.core.component.inject @DelicateCoroutinesApi class UnitsViewModel( savedStateHandle: SavedStateHandle ) : ViewModel(), KoinComponent { enum class UnitsDisplayMode { MAP, LIST } private val unitsController: UnitsController by inject() var searchQuery = savedStateHandle.getLiveData("searchQuery", "") var unitsDisplayMode = MutableLiveData(UnitsDisplayMode.LIST) var units = MutableLiveData>() init { Log.d("UnitsViewModel", "Initializing Units View Model") viewModelScope.launch { setupObservers() } } private suspend fun setupObservers() { Log.d("UnitsViewModel", "Setup observers") unitsController.displayedUnitsFlow.collect { units -> this.units.value = units } } fun toggleDisplayMode() { Log.d("UnitsViewModel", "Toggling Display mode") val newDisplayMode = if (unitsDisplayMode.value == UnitsDisplayMode.MAP) { UnitsDisplayMode.LIST } else { UnitsDisplayMode.MAP } unitsDisplayMode.postValue(newDisplayMode) } fun search() { unitsController.search(searchQuery.value!!) } }