aboutsummaryrefslogtreecommitdiff
path: root/androidApp/src/main/java/mx/trackermap/TrackerMap/android/details/reports/UnitReportsFragment.kt
blob: 60ad531ee823072a16f892fe257311fce73adb95 (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
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
/**
 * TrackerMap
 * Copyright (C) 2021-2022  Iván Ávalos <avalos@disroot.org>, Henoch Ojeda <imhenoch@protonmail.com>
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program. If not, see <http://www.gnu.org/licenses/>.
 */
package mx.trackermap.TrackerMap.android.details.reports

import android.app.Activity
import android.content.Intent
import android.os.Build
import android.os.Bundle
import android.os.Environment
import android.provider.DocumentsContract
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.PopupMenu
import android.widget.TableRow
import android.widget.TextView
import androidx.activity.result.contract.ActivityResultContracts
import androidx.core.view.setMargins
import androidx.fragment.app.Fragment
import androidx.fragment.app.commit
import kotlinx.coroutines.DelicateCoroutinesApi
import mx.trackermap.TrackerMap.android.R
import mx.trackermap.TrackerMap.android.databinding.UnitDetailsReportsBinding
import mx.trackermap.TrackerMap.android.details.UnitDetailsAdapter
import mx.trackermap.TrackerMap.android.map.MapWrapperFragment
import mx.trackermap.TrackerMap.android.shared.FileCache
import mx.trackermap.TrackerMap.android.shared.Utils
import mx.trackermap.TrackerMap.client.models.EventInformation
import mx.trackermap.TrackerMap.controllers.ReportController
import mx.trackermap.TrackerMap.utils.Formatter
import mx.trackermap.TrackerMap.utils.ReportDates
import org.koin.androidx.viewmodel.ext.android.viewModel
import java.io.*
import kotlin.math.max
import kotlin.time.ExperimentalTime

@DelicateCoroutinesApi
@ExperimentalTime
class UnitReportsFragment : Fragment() {

    private var _binding: UnitDetailsReportsBinding? = null
    private val binding get() = _binding!!

    private val unitReportsViewModel: UnitReportsViewModel by viewModel()
    private lateinit var mapFragment: MapWrapperFragment

    private var reportFile: ReportController.Report.XlsxReport? = null
    private var exportAction: UnitReportsViewModel.ExportAction? = null

    private companion object {
        const val XLSX_MIME_TYPE = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
    }

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        _binding = UnitDetailsReportsBinding.inflate(inflater, container, false)
        return binding.root
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

        unitReportsViewModel.setDeviceId(
            arguments?.getInt(UnitDetailsAdapter.DEVICE_ID_ARG) ?: 0)
        setupEvents()
        initializeMap()
    }

    override fun onResume() {
        super.onResume()

        setupObservers()
    }

    override fun onPause() {
        super.onPause()

        removeObservers()

        if (unitReportsViewModel.report.value == null) {
            unitReportsViewModel.fetchReport()
        }
    }

    override fun onDestroyView() {
        super.onDestroyView()
        _binding = null
    }

    private fun initializeMap() {
        Log.d("UnitReportsFragment", "initializeMap()")
        mapFragment = MapWrapperFragment.newInstance(
            showLayerToggle = true
        )
        childFragmentManager.commit {
            replace(R.id.reportsMapContainer, mapFragment)
        }
    }

    private fun setupEvents() {
        binding.reportType.setOnPositionChangedListener { position ->
            unitReportsViewModel.setReportType(
                when (position) {
                    0 -> ReportController.ReportType.POSITIONS
                    1 -> ReportController.ReportType.EVENTS
                    else -> ReportController.ReportType.STOPS
                }
            )
        }
        binding.periodButton.setOnClickListener {
            showPeriodPopUp(it)
        }
        binding.exportButton.setOnClickListener {
            exportAction = UnitReportsViewModel.ExportAction.ACTION_SAVE
            unitReportsViewModel.fetchReportXlsx()
        }
        binding.shareButton.setOnClickListener {
            exportAction = UnitReportsViewModel.ExportAction.ACTION_SHARE
            unitReportsViewModel.fetchReportXlsx()
        }
        unitReportsViewModel.setReportPeriod(ReportDates.ReportPeriod.TODAY)
        unitReportsViewModel.setReportType(ReportController.ReportType.POSITIONS)
    }

    private fun setupObservers() {
        Log.d("UnitReportsFragment", "Adding observers")
        unitReportsViewModel.report.observe(viewLifecycleOwner) { report ->
            Log.d("UnitReportsFragment", "Report available: $report")

            when (report) {
                is ReportController.Report.PositionsReport -> {
                    mapFragment.display(unitReportsViewModel.geofences.value!!)
                    mapFragment.display(report.positions.toTypedArray(), isReport = true, center = true)
                    showMap(true)
                }
                is ReportController.Report.EventsReport -> {
                    display(report.events.toTypedArray())
                    showMap(false)
                }
                is ReportController.Report.StopsReport -> {
                    mapFragment.display(unitReportsViewModel.geofences.value!!)
                    mapFragment.display(report.stops.toTypedArray())
                    showMap(true)
                }
                is ReportController.Report.XlsxReport -> {
                    reportFile = report
                    when (exportAction) {
                        UnitReportsViewModel.ExportAction.ACTION_SHARE -> shareFile()
                        UnitReportsViewModel.ExportAction.ACTION_SAVE -> saveFile()
                        else -> {}
                    }
                }
                is ReportController.Report.LoadingReport -> loading()
            }
        }

        unitReportsViewModel.reportPeriod.observe(viewLifecycleOwner) { period ->
            Log.d("UnitReportsFragment", "Period changed: $period")
            if (period == null) {
                return@observe
            }

            binding.periodButton.text = context?.getString(
                when (period) {
                    ReportDates.ReportPeriod.TODAY -> R.string.period_today
                    ReportDates.ReportPeriod.LAST_24 -> R.string.period_last_24
                    ReportDates.ReportPeriod.YESTERDAY -> R.string.period_yesterday
                    ReportDates.ReportPeriod.THIS_WEEK -> R.string.period_this_week
                    ReportDates.ReportPeriod.LAST_7 -> R.string.period_last_7
                    ReportDates.ReportPeriod.THIS_MONTH -> R.string.period_this_month
                    ReportDates.ReportPeriod.LAST_30 -> R.string.period_last_30
                }
            )
        }

        unitReportsViewModel.geofences.observe(viewLifecycleOwner) { geofences ->
            mapFragment.display(geofences)
        }
    }

    private fun removeObservers() {
        Log.d("UnitReportsFragment", "Removing observers")
        unitReportsViewModel.report.removeObservers(viewLifecycleOwner)
        unitReportsViewModel.reportPeriod.removeObservers(viewLifecycleOwner)
        unitReportsViewModel.clearReport()
    }

    private fun showPeriodPopUp(view: View) {
        val popOver = PopupMenu(context, view)
        popOver.menuInflater.inflate(R.menu.report_period_options, popOver.menu)
        popOver.setOnMenuItemClickListener { item ->
            unitReportsViewModel.setReportPeriod(
                when (item.itemId) {
                    R.id.optionToday -> ReportDates.ReportPeriod.TODAY
                    R.id.optionLast24 -> ReportDates.ReportPeriod.LAST_24
                    R.id.optionYesterday -> ReportDates.ReportPeriod.YESTERDAY
                    R.id.optionWeek -> ReportDates.ReportPeriod.THIS_WEEK
                    R.id.optionLast7 -> ReportDates.ReportPeriod.LAST_7
                    R.id.optionMonth -> ReportDates.ReportPeriod.THIS_MONTH
                    R.id.optionLast30 -> ReportDates.ReportPeriod.LAST_30
                    else -> ReportDates.ReportPeriod.TODAY
                }
            )
            true
        }
        popOver.show()
    }

    private fun display(events: Array<EventInformation>) {
        Log.d("UnitReportsFragment", "Displaying events: $events")

        binding.eventsScroll.visibility = View.VISIBLE
        binding.reportsMapContainer.visibility = View.GONE
        binding.eventsTable.removeViews(1, max(0, binding.eventsTable.childCount - 1))

        val context = requireContext()
        events.forEach { event ->
            val layoutParams = TableRow.LayoutParams()
            layoutParams.setMargins(
                resources.getDimensionPixelSize(R.dimen.padding)
            )
            val row = TableRow(context)
            val datetimeText = TextView(context)
            val eventText = TextView(context)
            val geofenceText = TextView(context)
            val addressText = TextView(context)

            datetimeText.layoutParams = layoutParams
            eventText.layoutParams = layoutParams
            geofenceText.layoutParams = layoutParams
            addressText.layoutParams = layoutParams

            row.addView(datetimeText)
            row.addView(eventText)
            row.addView(geofenceText)
            row.addView(addressText)
            binding.eventsTable.addView(row)

            event.event.eventTime?.let { it ->
                datetimeText.text = Formatter.formatDate(it)
            }
            event.event.type?.let {
                eventText.text = getString(
                    when (EventInformation.stringToReportType(it)) {
                        EventInformation.Type.DEVICE_ONLINE -> R.string.event_device_online
                        EventInformation.Type.DEVICE_UNKNOWN -> R.string.event_device_unknown
                        EventInformation.Type.DEVICE_OFFLINE -> R.string.event_device_offline
                        EventInformation.Type.DEVICE_INACTIVE -> R.string.event_device_inactive
                        EventInformation.Type.DEVICE_MOVING -> R.string.event_device_moving
                        EventInformation.Type.DEVICE_STOPPED -> R.string.event_device_stopped
                        EventInformation.Type.DEVICE_OVERSPEED -> R.string.event_device_overspeed
                        EventInformation.Type.DEVICE_FUEL_DROP -> R.string.event_device_fuel_drop
                        EventInformation.Type.COMMAND_RESULT -> R.string.event_command_result
                        EventInformation.Type.GEOFENCE_ENTER -> R.string.event_geofence_enter
                        EventInformation.Type.GEOFENCE_EXIT -> R.string.event_geofence_exit
                        EventInformation.Type.ALARM -> R.string.event_alarm
                        EventInformation.Type.IGNITION_ON -> R.string.event_ignition_on
                        EventInformation.Type.IGNITION_OFF -> R.string.event_ignition_off
                        EventInformation.Type.MAINTENANCE -> R.string.event_maintenance
                        EventInformation.Type.TEXT_MESSAGE -> R.string.event_text_message
                        EventInformation.Type.DRIVER_CHANGED -> R.string.event_driver_changed
                        EventInformation.Type.UNKNOWN ->  R.string.event_unknown
                        else -> R.string.event_unknown
                    })
            }
            event.geofence?.let {
                geofenceText.text = it.name
            }
            event.position?.let {
                addressText.text = it.address
            }
        }
    }

    private fun loading() {
        binding.reportLoading.root.visibility = View.VISIBLE
        binding.eventsScroll.visibility = View.GONE
        binding.reportsMapContainer.visibility = View.GONE

        childFragmentManager.commit {
            hide(mapFragment)
        }
    }

    private fun showMap(shouldShowMap: Boolean) {
        Log.d("UnitReportsFragment", "showMap($shouldShowMap)")
        binding.reportLoading.root.visibility = View.GONE
        binding.eventsScroll.visibility = if (shouldShowMap) View.GONE else View.VISIBLE
        binding.reportsMapContainer.visibility = if (shouldShowMap) View.VISIBLE else View.GONE

        childFragmentManager.commit {
            if (shouldShowMap) {
                show(mapFragment)
            } else {
                hide(mapFragment)
            }
        }
    }

    private fun saveFile(filename: String = "reports.xlsx") {
        val filesDir = requireContext().getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS)
        filesDir?.let {
            val intent = Intent(Intent.ACTION_CREATE_DOCUMENT).apply {
                addCategory(Intent.CATEGORY_OPENABLE)
                type = XLSX_MIME_TYPE
                putExtra(Intent.EXTRA_TITLE, filename)
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                    putExtra(DocumentsContract.EXTRA_INITIAL_URI, filesDir)
                }
            }
            createDocumentResult.launch(intent)
        }
    }

    private fun shareFile(filename: String = "reports.xlsx") {
        context?.let { context ->
            reportFile?.data?.let { data ->
                val cacheFile = Utils.saveReportToCache(context, data, filename)
                Utils.shareFile(context, cacheFile, XLSX_MIME_TYPE)
            }
        }
    }

    private val createDocumentResult =
        registerForActivityResult(ActivityResultContracts.StartActivityForResult()) {
            if (it.resultCode == Activity.RESULT_OK) {
                reportFile?.let { report ->
                    it?.data?.data?.also { uri ->
                        Log.d("UnitReportsFragment", "Downloading file into ${uri.path}")
                        val outputStream = context?.contentResolver?.openOutputStream(uri)
                        outputStream?.let {
                            try {
                                outputStream.write(report.data)
                                outputStream.flush()
                                outputStream.close()
                                Log.d("UnitReportsFragment", "Wrote file into ${uri.path}")

                                activity?.let { context ->
                                    // Copy file to cache so we can open it
                                    val fc = FileCache(context)
                                    fc.removeAll()
                                    fc.cacheThis(listOf(uri))

                                    val dir = File(context.cacheDir, "reports_tmp")
                                    val files = dir.listFiles()
                                    if (files?.isNotEmpty() == true) {
                                        val intent =
                                            Utils.openFileIntent(context, files[0], XLSX_MIME_TYPE)
                                        openFileResult.launch(intent)
                                    }
                                }

                            } catch (e: IOException) {
                                e.printStackTrace()
                            }
                        }
                    }
                }
            }
        }

    private val openFileResult =
        registerForActivityResult(ActivityResultContracts.StartActivityForResult()) {
            if (it.resultCode == Activity.RESULT_OK) {
                Log.d("UnitReportsFragment", "Opening file!")
            }
        }
}