Bimba.git

ref: 68ae37f62658ef2b5dfe364bfa283d03b4f35951

app/src/main/java/xyz/apiote/bimba/czwek/departures/DeparturesActivity.kt


  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
// SPDX-FileCopyrightText: Adam Evyčędo
//
// SPDX-License-Identifier: GPL-3.0-or-later

package xyz.apiote.bimba.czwek.departures

import android.content.Intent
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.text.format.DateUtils
import android.text.format.DateUtils.MINUTE_IN_MILLIS
import android.view.View
import androidx.appcompat.app.AppCompatActivity
import androidx.appcompat.content.res.AppCompatResources
import androidx.core.content.res.ResourcesCompat
import androidx.core.view.WindowCompat
import androidx.lifecycle.ViewModelProvider
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.google.android.material.datepicker.MaterialDatePicker
import com.google.android.material.dialog.MaterialAlertDialogBuilder
import com.google.android.material.snackbar.Snackbar
import com.google.android.material.timepicker.MaterialTimePicker
import com.google.android.material.timepicker.TimeFormat
import kotlinx.coroutines.Runnable
import xyz.apiote.bimba.czwek.R
import xyz.apiote.bimba.czwek.api.Error
import xyz.apiote.bimba.czwek.databinding.ActivityDeparturesBinding
import xyz.apiote.bimba.czwek.repo.Departure
import xyz.apiote.bimba.czwek.repo.Stop
import java.time.Instant
import java.time.LocalDate
import java.time.LocalTime
import java.time.ZoneId
import java.time.ZonedDateTime

class DeparturesActivity : AppCompatActivity() {
	private var _binding: ActivityDeparturesBinding? = null
	private val binding get() = _binding!!

	private lateinit var adapter: BimbaDeparturesAdapter

	private val handler = Handler(Looper.getMainLooper())
	private var runnable = Runnable {}

	private var openBottomSheet: DepartureBottomSheet? = null
	private lateinit var snackbar: Snackbar

	private lateinit var viewModel: DeparturesViewModel

	private val datePicker =
		MaterialDatePicker.Builder.datePicker().setTitleText(R.string.title_select_date)
			.setNegativeButtonText(R.string.clear_date_selection)
			.build()
	private var timePickerStart: MaterialTimePicker? = null
	private var timePickerEnd: MaterialTimePicker? = null
	private var linePicker: MaterialAlertDialogBuilder? = null
	private var date: LocalDate? = null
	private val linesFilter = mutableMapOf<String, Boolean>()
	private val linesFilterTemporary = mutableMapOf<String, Boolean>()
	private var startTime: LocalTime = LocalTime.MIN
	private var endTime: LocalTime = LocalTime.MAX

	override fun onCreate(savedInstanceState: Bundle?) {
		super.onCreate(savedInstanceState)
		_binding = ActivityDeparturesBinding.inflate(layoutInflater)
		setContentView(binding.root)

		viewModel = ViewModelProvider(this)[DeparturesViewModel::class.java]

		linePicker = MaterialAlertDialogBuilder(this)
			.setTitle(resources.getString(R.string.title_select_line))
			.setNegativeButton(R.string.clear_date_selection) { _, _ ->
				linesFilter.clear()
				getDepartures()
			}
			.setPositiveButton(R.string.ok) { _, _ ->
				linesFilterTemporary.forEach { linesFilter[it.key] = it.value }
				getDepartures()
			}

		viewModel.departures.observe(this) { stopDepartures ->
			updateItems(
				stopDepartures.departures
					.filter { d ->
						linesFilter.values.all { !it } or (linesFilter[d.vehicle.Line.name] ?: false)
					}
					.filter { d ->
						val t = LocalTime.of(d.time.Hour.toInt(), d.time.Minute.toInt())
						t >= startTime && t <= endTime
					},
				stopDepartures.stop
			)
			openBottomSheet?.departureID()?.let { adapter.get(it) }?.let { openBottomSheet?.update(it) }

			val lines = stopDepartures.departures.map { it.vehicle.Line.name }.sortedWith { s1, s2 ->
				val s1n = s1.toIntOrNull()
				val s2n = s2.toIntOrNull()
				if (s1n != null && s2n != null) {
					s1.toInt() - s2.toInt()
				} else {
					s1.compareTo(s2)
				}
			}.toSet().toTypedArray()
			val selections = lines.map { linesFilter.getOrDefault(it, false) }.toBooleanArray()

			linePicker?.setMultiChoiceItems(lines, selections) { _, which, checked ->
				linesFilterTemporary[lines[which]] = checked
			}
		}
		viewModel.error.observe(this) {
			showError(it)
		}

		binding.departuresAppBar.menu.findItem(R.id.departures_filter_bytime).setEnabled(false)


		datePicker.addOnNegativeButtonClickListener {
			date = null
			binding.departuresAppBar.menu.findItem(R.id.departures_filter_bytime).setEnabled(false)
			getDepartures()  // TODO force clear and error
		}
		datePicker.addOnPositiveButtonClickListener {
			if (date == null) {
				startTime = LocalTime.MIN
				endTime = LocalTime.MAX
			}
			date = Instant.ofEpochMilli(it).atZone(ZoneId.systemDefault())
				.toLocalDate()
			binding.departuresAppBar.menu.findItem(R.id.departures_filter_bytime).setEnabled(true)
			getDepartures()  // TODO force clear and error
		}

		binding.collapsingLayout.apply {
			title = getName()
			val tf = ResourcesCompat.getFont(this@DeparturesActivity, R.font.yellowcircle8)
			setCollapsedTitleTypeface(tf)
			setExpandedTitleTypeface(tf)
		}
		binding.departuresAppBar.setOnMenuItemClickListener {
			when (it.itemId) {
				R.id.departures_calendar -> {
					datePicker.show(supportFragmentManager, "datePicker")
					true
				}

				R.id.departures_filter_byline -> {
					linesFilterTemporary.clear()
					linesFilter.forEach { filter -> linesFilterTemporary[filter.key] = filter.value }
					linePicker?.show()
					true
				}

				R.id.departures_filter_bytime -> {
					timePickerStart =
						MaterialTimePicker.Builder().setTitleText(R.string.title_select_time_start)
							.setTimeFormat(TimeFormat.CLOCK_24H)
							.setHour(startTime.hour)
							.setMinute(startTime.minute)
							.setNegativeButtonText(R.string.clear_date_selection)
							.build()
					timePickerEnd = MaterialTimePicker.Builder().setTitleText(R.string.title_select_time_end)
						.setTimeFormat(TimeFormat.CLOCK_24H)
						.setHour(endTime.hour)
						.setMinute(endTime.minute)
						.setNegativeButtonText(R.string.clear_date_selection)
						.build()
					timePickerEnd!!.addOnPositiveButtonClickListener {
						endTime = LocalTime.of(timePickerEnd!!.hour, timePickerEnd!!.minute)
						getDepartures()  // TODO force clear and error
					}
					timePickerEnd!!.addOnNegativeButtonClickListener {
						endTime = LocalTime.MAX
						getDepartures()  // TODO force clear and error
					}
					timePickerStart!!.addOnPositiveButtonClickListener {
						startTime = LocalTime.of(timePickerStart!!.hour, timePickerStart!!.minute)
						timePickerEnd!!.show(supportFragmentManager, "timePickerEnd")
					}
					timePickerStart!!.addOnNegativeButtonClickListener {
						startTime = LocalTime.MIN
						timePickerEnd!!.show(supportFragmentManager, "timePickerEnd")
					}
					timePickerStart!!.show(supportFragmentManager, "timePickerStart")
					true
				}

				else -> super.onOptionsItemSelected(it)
			}
		}

		binding.departuresRecycler.layoutManager = LinearLayoutManager(this)
		binding.departuresRecycler.addOnScrollListener(
			object : RecyclerView.OnScrollListener() {
				override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
					super.onScrolled(recyclerView, dx, dy)
					val llm = binding.departuresRecycler.layoutManager as LinearLayoutManager
					val dataLength = adapter.itemCount
					if (llm.findLastCompletelyVisibleItemPosition() == dataLength - 1) {
						if (!viewModel.allItemsRequested) {
							viewModel.requestedItemsNumber += 12
							getDepartures()
						}
					}
				}
			}
		)
		adapter = BimbaDeparturesAdapter(layoutInflater, this, listOf()) {
			DepartureBottomSheet(it).apply {
				show(supportFragmentManager, DepartureBottomSheet.TAG)
				openBottomSheet = this
				setOnCancel { openBottomSheet = null }
			}
		}
		binding.departuresRecycler.adapter = adapter
		WindowCompat.setDecorFitsSystemWindows(window, false)

		snackbar = Snackbar.make(binding.root, "", Snackbar.LENGTH_INDEFINITE)
	}

	override fun onResume() {
		super.onResume()
		getDepartures()
	}

	override fun onPause() {
		super.onPause()
		handler.removeCallbacks(runnable)
	}

	private fun getName(): String {
		return when (intent?.action) {
			Intent.ACTION_VIEW -> getString(R.string.stop_from_qr_code)
			null -> intent?.extras?.getString("name") ?: ""
			else -> ""
		}
	}

	private fun getLine(): String? {
		return when (intent?.action) {
			null -> intent?.extras?.getString("line")
			else -> null
		}
	}

	fun getDepartures() {
		adapter.refreshItems()
		setupSnackbar()
		viewModel.getDepartures(this, getLine(), date)
		handler.removeCallbacks(runnable)
		runnable = Runnable { getDepartures() }
		handler.postDelayed(runnable, 30 * 1000)
	}

	private fun setupSnackbar() {
		val lastUpdateAgo = ZonedDateTime.now().toEpochSecond() - adapter.lastUpdate.toEpochSecond()
		if (lastUpdateAgo > 59 && adapter.lastUpdate.year != 0) {
			snackbar.setText(
				getString(
					R.string.departures_snackbar,
					DateUtils.getRelativeTimeSpanString(
						adapter.lastUpdate.toEpochSecond() * 1000,
						ZonedDateTime.now().toEpochSecond() * 1000,
						MINUTE_IN_MILLIS,
						DateUtils.FORMAT_ABBREV_RELATIVE
					)
				)
			).show()
		} else {
			snackbar.dismiss()
		}
	}

	private fun showError(error: Error) {
		binding.departuresProgress.visibility = View.GONE
		binding.departuresRecycler.visibility = View.GONE
		binding.errorImage.visibility = View.VISIBLE
		binding.errorText.visibility = View.VISIBLE

		binding.errorText.text = getString(error.stringResource)
		binding.errorImage.setImageDrawable(
			AppCompatResources.getDrawable(
				this,
				error.imageResource
			)
		)
	}

	private fun updateItems(departures: List<Departure>, stop: Stop) {
		setupSnackbar()
		binding.departuresProgress.visibility = View.GONE
		adapter.update(departures, date != null, true)
		binding.collapsingLayout.apply {
			title = stop.name
		}
		if (departures.isEmpty()) {
			binding.errorImage.visibility = View.VISIBLE
			binding.errorText.visibility = View.VISIBLE
			binding.departuresRecycler.visibility = View.GONE

			binding.errorText.text = getString(R.string.no_departures)
			binding.errorImage.setImageDrawable(
				AppCompatResources.getDrawable(
					this, R.drawable.error_search
				)
			)
		} else {
			if (departures.size < viewModel.requestedItemsNumber) {
				viewModel.allItemsRequested = true
			}
			binding.departuresOverlay.visibility = View.GONE
			binding.errorImage.visibility = View.GONE
			binding.errorText.visibility = View.GONE
			binding.departuresRecycler.visibility = View.VISIBLE
		}
		// todo [3.2; traffic] alerts
		// todo [3.2; traffic] stop info
	}
}