aboutsummaryrefslogtreecommitdiff
path: root/androidApp/src/main/java/mx/trackermap/TrackerMap/android/details/reports/UnitReportsViewModel.kt
blob: 48486e1a192129915a753c8ec15226c07ac3463c (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
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
package mx.trackermap.TrackerMap.android.details.reports

import android.util.Log
import androidx.lifecycle.*
import kotlinx.coroutines.DelicateCoroutinesApi
import java.text.SimpleDateFormat
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.launch
import mx.trackermap.TrackerMap.client.apis.ReportsApi
import mx.trackermap.TrackerMap.client.models.*
import mx.trackermap.TrackerMap.controllers.GeofencesController
import org.koin.core.component.KoinComponent
import org.koin.core.component.inject
import java.util.*
import java.util.Calendar

@DelicateCoroutinesApi
class UnitReportsViewModel(
    private val reportsApi: ReportsApi,
    savedStateHandle: SavedStateHandle
) : ViewModel(), KoinComponent {

    sealed class Report {
        class PositionsReport(val positions: Array<Position>) : Report()
        class EventsReport(val events: Array<EventInformation>) : Report()
        class StopsReport(val stops: Array<Stop>) : Report()
        object LoadingReport: Report()
    }

    enum class ReportType {
        POSITIONS, EVENTS, STOPS
    }

    enum class ReportPeriod {
        DAY, WEEK, MONTH
    }

    private val geofenceController: GeofencesController by inject()

    private var _deviceId = savedStateHandle.getLiveData("deviceId", 0)
    private val _reportType: MutableLiveData<ReportType> = savedStateHandle.getLiveData("reportType", null)
    private val _reportPeriod: MutableLiveData<ReportPeriod> =
        savedStateHandle.getLiveData("reportPeriod", null)
    private val _report: MutableLiveData<Report> = MutableLiveData()
    private val _geofences: MutableLiveData<Map<Int, Geofence>> = MutableLiveData()

    val deviceId: LiveData<Int> get() = _deviceId
    val reportType: LiveData<ReportType> get() = _reportType
    val reportPeriod: LiveData<ReportPeriod> get() = _reportPeriod
    val report: LiveData<Report> get() = _report
    val geofences: LiveData<Map<Int, Geofence>> get() = _geofences

    private val dateFormat = SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'", Locale.getDefault())

    init {
        viewModelScope.launch {
            setupTypeObserver()
        }
        viewModelScope.launch {
            setupPeriodObserver()
        }
        viewModelScope.launch {
            setupGeofenceObserver()
        }
    }

    private suspend fun setupTypeObserver() {
        _reportType.asFlow().collect {
            fetchReport()
        }
    }

    private suspend fun setupPeriodObserver() {
        _reportPeriod.asFlow().collect {
            fetchReport()
        }
    }

    private suspend fun setupGeofenceObserver() {
        geofenceController.geofencesFlow.collect {
            _geofences.postValue(it)
        }
    }

    fun setDeviceId (id: Int) {
        _deviceId.value = id
    }

    fun setReportType(reportType: ReportType) {
        _reportType.value = reportType
    }

    fun setReportPeriod(reportPeriod: ReportPeriod) {
        _reportPeriod.value = reportPeriod
    }

    fun getGeofence(id: Int): Geofence? = _geofences.value?.get(id)

    private fun getDates(): Pair<Date, Date> {
        val calendar = Calendar.getInstance()
        val currentDate = calendar.time

        calendar.add(
            Calendar.DATE, when (_reportPeriod.value!!) {
                ReportPeriod.DAY -> -1
                ReportPeriod.WEEK -> -7
                ReportPeriod.MONTH -> -30
            }
        )
        val previousDate = calendar.time

        return Pair(currentDate, previousDate)
    }

    private fun fetchReport() {
        if (_reportType.value == null || _reportPeriod.value == null) {
            return
        }

        val (currentDate, previousDate) = getDates()
        Log.d("UnitReportsVM", "Current report type: ${_reportType.value.toString()}")
        Log.d("UnitReportsVM", "Current report period: ${_reportPeriod.value.toString()}")
        Log.d("UnitReportsVM", "Current date:${dateFormat.format(currentDate)}")
        Log.d("UnitReportsVM", "Previous date:${dateFormat.format(previousDate)}")

        _report.postValue(Report.LoadingReport)
        viewModelScope.launch {
            when (_reportType.value!!) {
                ReportType.POSITIONS -> fetchPositions(previousDate, currentDate)
                ReportType.EVENTS -> fetchEvents(previousDate, currentDate)
                ReportType.STOPS -> fetchStops(previousDate, currentDate)
            }
        }
    }

    private suspend fun fetchPositions(from: Date, to: Date) {
        Log.d("UnitReportsVM", "Fetching positions")

        val result = reportsApi.reportsRouteGet(
            dateFormat.format(from),
            dateFormat.format(to),
            _deviceId.value!!
        )

        Log.d("UnitReportsVM", "Positions report: $result")
        _report.postValue(Report.PositionsReport(result))
    }

    private suspend fun fetchEvents(from: Date, to: Date) {
        Log.d("UnitReportsVM", "Fetching events")

        val positionsResult = reportsApi.reportsRouteGet(
            dateFormat.format(from),
            dateFormat.format(to),
            _deviceId.value!!
        )

        val eventsResult = reportsApi.reportsEventsGet(
            dateFormat.format(from),
            dateFormat.format(to),
            _deviceId.value!!
        )

        val result = mutableListOf<EventInformation>()

        eventsResult.forEach { event ->
            result.add(EventInformation(
                event = event,
                position = positionsResult.find { it.id == event.positionId }
            ))
        }

        Log.d("UnitReportsVM", "Events report: $result")
        _report.postValue(Report.EventsReport(result.toTypedArray()))
    }

    private suspend fun fetchStops(from: Date, to: Date) {
        Log.d("UnitReportsVM", "Fetching stops")

        val result = reportsApi.reportsStopsGet(
            dateFormat.format(from),
            dateFormat.format(to),
            _deviceId.value!!
        )

        Log.d("UnitReportsVM", "Stops report: $result")
        _report.postValue(Report.StopsReport(result))
    }
}