aboutsummaryrefslogtreecommitdiff
path: root/androidApp/src/main/java/mx/trackermap/TrackerMap/android/units/UnitsViewModel.kt
blob: bb4efde8174fda9c01f2a7e79578053692fb67e5 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
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<List<UnitInformation>>()
    var selectedUnit = MutableLiveData<UnitInformation?>()

    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 selectUnit(unit: UnitInformation) {
        Log.d("UnitsViewModel", "Selecting unit ${unit.device.name}")
        selectedUnit.postValue(unit)
        setDisplayMode(UnitsDisplayMode.MAP)
    }

    fun setDisplayMode(displayMode: UnitsDisplayMode) {
        Log.d("UnitsViewModel", "Setting Display mode to $displayMode")
        unitsDisplayMode.postValue(displayMode)
    }

    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!!)
    }
}