blob: 865f096617b514cc1475da0294b736b7c987c615 (
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
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
|
package mx.trackermap.TrackerMap.android.details.reports
import androidx.lifecycle.*
import kotlinx.coroutines.DelicateCoroutinesApi
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.launch
import mx.trackermap.TrackerMap.controllers.ReportController
import mx.trackermap.TrackerMap.utils.ReportDates
import org.koin.core.component.KoinComponent
import org.koin.core.component.inject
@DelicateCoroutinesApi
class UnitReportsViewModel(
savedStateHandle: SavedStateHandle
) : ViewModel(), KoinComponent {
private val reportController: ReportController by inject()
private var _deviceId = savedStateHandle.getLiveData("deviceId", 0)
private val _reportType: MutableLiveData<ReportController.ReportType> = savedStateHandle.getLiveData("reportType", null)
private val _reportPeriod: MutableLiveData<ReportDates.ReportPeriod> =
savedStateHandle.getLiveData("reportPeriod", null)
private val _report: MutableLiveData<ReportController.Report> = MutableLiveData()
val deviceId: LiveData<Int> get() = _deviceId
val reportType: LiveData<ReportController.ReportType> get() = _reportType
val reportPeriod: LiveData<ReportDates.ReportPeriod> get() = _reportPeriod
val report: LiveData<ReportController.Report> get() = _report
init {
viewModelScope.launch {
setupTypeObserver()
}
viewModelScope.launch {
setupPeriodObserver()
}
viewModelScope.launch {
setupReportObserver()
}
}
private suspend fun setupTypeObserver() {
_reportType.asFlow().collect {
fetchReport()
}
}
private suspend fun setupPeriodObserver() {
_reportPeriod.asFlow().collect {
fetchReport()
}
}
private suspend fun setupReportObserver() {
reportController.reportFlow.collect {
_report.value = it
}
}
fun setDeviceId (id: Int) {
_deviceId.value = id
}
fun setReportType(reportType: ReportController.ReportType) {
_reportType.value = reportType
}
fun setReportPeriod(reportPeriod: ReportDates.ReportPeriod) {
_reportPeriod.value = reportPeriod
}
fun fetchReportXlsx() {
fetchReport(true)
}
private fun fetchReport(xlsx: Boolean = false) {
if (_reportType.value == null || _reportPeriod.value == null) {
return
}
viewModelScope.launch {
_deviceId.value?.let { id ->
reportController.fetchReport(
deviceId = id,
reportType = _reportType.value,
reportPeriod = _reportPeriod.value,
xlsx = xlsx
)
}
}
}
}
|