Bimba.git

ref: e4d7079147c16b0d67cd39e35f5d943644d24c68

app/src/main/java/xyz/apiote/bimba/czwek/search/ResultsActivity.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
321
322
323
324
325
326
327
328
329
330
331
// SPDX-FileCopyrightText: Adam Evyčędo
//
// SPDX-License-Identifier: GPL-3.0-or-later

package xyz.apiote.bimba.czwek.search

import android.content.Context
import android.content.Intent
import android.hardware.Sensor
import android.hardware.SensorEvent
import android.hardware.SensorEventListener
import android.hardware.SensorManager
import android.location.Location
import android.location.LocationListener
import android.location.LocationManager
import android.os.Build
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.util.Log
import android.view.View
import android.view.ViewGroup.MarginLayoutParams
import androidx.activity.enableEdgeToEdge
import androidx.appcompat.app.AppCompatActivity
import androidx.appcompat.content.res.AppCompatResources
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import androidx.core.view.updateLayoutParams
import androidx.core.view.updatePadding
import androidx.recyclerview.widget.LinearLayoutManager
import com.google.openlocationcode.OpenLocationCode
import kotlinx.coroutines.MainScope
import kotlinx.coroutines.Runnable
import kotlinx.coroutines.launch
import xyz.apiote.bimba.czwek.R
import xyz.apiote.bimba.czwek.api.Error
import xyz.apiote.bimba.czwek.databinding.ActivityResultsBinding
import xyz.apiote.bimba.czwek.repo.OfflineRepository
import xyz.apiote.bimba.czwek.repo.OnlineRepository
import xyz.apiote.bimba.czwek.repo.Position
import xyz.apiote.bimba.czwek.repo.Queryable
import xyz.apiote.bimba.czwek.repo.TrafficResponseException
import xyz.apiote.bimba.czwek.settings.feeds.FeedsSettings

class ResultsActivity : AppCompatActivity(), LocationListener, SensorEventListener {
	enum class Mode {
		MODE_LOCATION, MODE_SEARCH, MODE_POSITION, MODE_SHORT_CODE_LOCATION, MODE_SHORT_CODE
	}

	companion object {
		const val MODE_KEY = "mode"
		const val QUERY_KEY = "query"
		const val LATITUDE_KEY = "lat"
		const val LONGITUDE_KEY = "lon"
		fun getIntent(
			context: Context,
			mode: Mode,
			query: String,
			latitude: Double,
			longitude: Double
		) =
			Intent(context, ResultsActivity::class.java).apply {
				putExtra(MODE_KEY, mode)
				putExtra(QUERY_KEY, query)
				putExtra(LATITUDE_KEY, latitude)
				putExtra(LONGITUDE_KEY, longitude)
			}

		fun getIntent(context: Context, mode: Mode, query: String) =
			Intent(context, ResultsActivity::class.java).apply {
				putExtra(MODE_KEY, mode)
				putExtra(QUERY_KEY, query)
			}

	}

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

	private lateinit var adapter: BimbaResultsAdapter

	private val handler = Handler(Looper.getMainLooper())
	private var runnable = Runnable {}
	private var gravity: FloatArray? = null
	private var geomagnetic: FloatArray? = null
	private var shortOLC: OpenLocationCode? = null

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

		ViewCompat.setOnApplyWindowInsetsListener(binding.resultsRecycler) { v, windowInsets ->

			windowInsets.displayCutout?.safeInsetLeft?.let {
				v.updateLayoutParams<MarginLayoutParams> {
					leftMargin = it
				}
			}
			val insets = windowInsets.getInsets(WindowInsetsCompat.Type.systemBars())
			v.updatePadding(right = insets.right, left = insets.left)
			windowInsets
		}
		ViewCompat.setOnApplyWindowInsetsListener(binding.topAppBar) { v, windowInsets ->
			val insets = windowInsets.getInsets(WindowInsetsCompat.Type.systemBars())
			v.updatePadding(right = insets.right, left = insets.left)
			windowInsets
		}

		binding.resultsRecycler.layoutManager = LinearLayoutManager(this)
		adapter = BimbaResultsAdapter(layoutInflater, this, listOf(), null, null, false)
		binding.resultsRecycler.adapter = adapter

		when (getMode()) {
			Mode.MODE_LOCATION -> {
				supportActionBar?.title = getString(R.string.stops_nearby)
				locate()
			}

			Mode.MODE_SHORT_CODE_LOCATION -> {
				val query = intent.extras?.getString(QUERY_KEY)
				supportActionBar?.title = getString(R.string.stops_near_code, query)
				shortOLC = OpenLocationCode(query)
				locate()
			}

			Mode.MODE_SHORT_CODE -> {
				val query = intent.extras?.getString(QUERY_KEY)
				supportActionBar?.title = getString(R.string.stops_near_code, query)
				val split = query!!.trim().split(" ")
				val code = split.first().trim(',').trim()
				val freePart = split.drop(1).joinToString(" ")
				val location = findPlace(this, freePart)
				if (location == null) {
					showError(Error(0, R.string.error_geocoding, R.drawable.geocoding))
				} else {
					val area = OpenLocationCode(code).recover(location.latitude, location.longitude).decode()
					getQueryablesByLocation(Location(null).apply {
						latitude = area.centerLatitude
						longitude = area.centerLongitude
					}, this)
				}
			}

			Mode.MODE_POSITION -> {
				val query = intent.extras?.getString(QUERY_KEY)
				val lat = intent.extras?.getDouble(LATITUDE_KEY)
				val lon = intent.extras?.getDouble(LONGITUDE_KEY)
				supportActionBar?.title = getString(R.string.stops_near_code, query)
				getQueryablesByLocation(Location(null).apply {
					latitude = lat!!
					longitude = lon!!
				}, this)
			}

			Mode.MODE_SEARCH -> {
				val query = intent.extras?.getString(QUERY_KEY)!!
				supportActionBar?.title = getString(R.string.results_for, query)
				getQueryablesByQuery(query, this)
			}
		}
	}

	private fun getMode(): Mode {
		return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
			intent.extras!!.getSerializable(MODE_KEY, Mode::class.java)!!
		} else {
			@Suppress("DEPRECATION")
			intent.extras!!.get(MODE_KEY) as Mode
		}
	}

	private fun locate() {
		val sensorManager = getSystemService(SENSOR_SERVICE) as SensorManager
		val accelerometer = sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER)
		val magnetometer = sensorManager.getDefaultSensor(Sensor.TYPE_MAGNETIC_FIELD)
		sensorManager.registerListener(this, accelerometer, SensorManager.SENSOR_DELAY_NORMAL)
		sensorManager.registerListener(this, magnetometer, SensorManager.SENSOR_DELAY_NORMAL)

		try {
			val locationManager = getSystemService(Context.LOCATION_SERVICE) as LocationManager
			locationManager.requestLocationUpdates(
				LocationManager.GPS_PROVIDER, 1000 * 60 * 10, 100f, this
			)
			handler.removeCallbacks(runnable)
			runnable = Runnable {
				showError(Error(0, R.string.error_gps, R.drawable.error_gps))
			}
			handler.postDelayed(runnable, 60 * 1000)
			locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER)
				?.let { onLocationChanged(it) }
		} catch (_: SecurityException) {
			Log.wtf(
				"locate",
				"this shouldn’t happen because we don’t start this activity without location permission"
			)
		}
	}

	override fun onLocationChanged(location: Location) {
		handler.removeCallbacks(runnable)
		val area = shortOLC?.recover(location.latitude, location.longitude)?.decode()
		if (area != null) {
			getQueryablesByLocation(Location(null).apply {
				latitude = area.centerLatitude
				longitude = area.centerLongitude
			}, this, false)
		} else {
			getQueryablesByLocation(location, this, true)
		}
	}

	override fun onAccuracyChanged(sensor: Sensor?, accuracy: Int) {}
	override fun onSensorChanged(event: SensorEvent?) {
		if (event?.sensor?.type == Sensor.TYPE_ACCELEROMETER) gravity = event.values
		if (event?.sensor?.type == Sensor.TYPE_MAGNETIC_FIELD) geomagnetic = event.values
		if (gravity != null && geomagnetic != null) {
			val r = FloatArray(9)
			val success = SensorManager.getRotationMatrix(r, FloatArray(9), gravity, geomagnetic)
			if (success) {
				val orientation = FloatArray(3)
				SensorManager.getOrientation(r, orientation)
				adapter.update((orientation[0] * 180 / Math.PI).toFloat())
			}
		}
	}

	override fun onResume() {
		super.onResume()
		if (getMode() == Mode.MODE_LOCATION) {
			locate()
		}
	}

	override fun onPause() {
		super.onPause()
		val locationManager = getSystemService(Context.LOCATION_SERVICE) as LocationManager
		locationManager.removeUpdates(this)
		handler.removeCallbacks(runnable)
		val sensorManager = getSystemService(SENSOR_SERVICE) as SensorManager
		sensorManager.unregisterListener(this)
	}

	override fun onDestroy() {
		super.onDestroy()
		val locationManager = getSystemService(Context.LOCATION_SERVICE) as LocationManager
		locationManager.removeUpdates(this)
		handler.removeCallbacks(runnable)
	}

	private suspend fun getFeeds() {
		if (adapter.feeds.isNullOrEmpty()) {
			val repository = OfflineRepository(this)
			adapter.feeds = repository.getFeeds(this)
			repository.close()
		}
		if (adapter.feedsSettings == null) {
			adapter.feedsSettings = FeedsSettings.load(this)
		}
	}

	private fun getQueryablesByQuery(query: String, context: Context) {
		MainScope().launch {
			try {
				val repository = OnlineRepository()
				val result = repository.queryQueryables(query, context)
				getFeeds()
				updateItems(result, null, false)
			} catch (e: TrafficResponseException) {
				Log.w("Suggestion", "$e")
				showError(e.error)
			}
		}
	}

	private fun getQueryablesByLocation(
		position: Location,
		context: Context,
		showArrow: Boolean = false
	) {
		MainScope().launch {
			try {
				val repository = OnlineRepository()
				val result =
					repository.locateQueryables(Position(position.latitude, position.longitude), context)
				getFeeds()
				updateItems(result, position, showArrow)
			} catch (e: TrafficResponseException) {
				Log.w("Suggestion", "$e")
				showError(e.error)
			}
		}
	}

	private fun showError(error: Error) {
		binding.resultsProgress.visibility = View.GONE
		binding.resultsRecycler.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(queryables: List<Queryable>?, position: Location?, showArrow: Boolean) {
		binding.resultsProgress.visibility = View.GONE
		adapter.update(queryables, position, showArrow)
		if (queryables.isNullOrEmpty()) {
			binding.errorImage.visibility = View.VISIBLE
			binding.errorText.visibility = View.VISIBLE
			binding.resultsRecycler.visibility = View.GONE

			binding.errorText.text = getString(R.string.error_404)
			binding.errorImage.setImageDrawable(
				AppCompatResources.getDrawable(
					this,
					R.drawable.error_search
				)
			)
		} else {
			if (queryables.size == 1 && getMode() == Mode.MODE_SEARCH) {
				adapter.click(0)
			}
			binding.resultsOverlay.visibility = View.GONE
			binding.errorImage.visibility = View.GONE
			binding.errorText.visibility = View.GONE
			binding.resultsRecycler.visibility = View.VISIBLE
		}
	}
}