-
Notifications
You must be signed in to change notification settings - Fork 0
/
MountainsRepository.kt
148 lines (133 loc) · 4.42 KB
/
MountainsRepository.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
// Copyright 2024 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.example.mountainmarkers.data.local
import android.content.Context
import android.util.Xml
import com.example.mountainmarkers.R
import com.example.mountainmarkers.data.utils.meters
import com.google.android.gms.maps.model.LatLng
import dagger.hilt.android.qualifiers.ApplicationContext
import java.io.IOException
import java.io.InputStream
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.withContext
import org.xmlpull.v1.XmlPullParser
import org.xmlpull.v1.XmlPullParserException
/**
* Repository for loading the list of mountain peaks.
*/
class MountainsRepository(@ApplicationContext val context: Context) {
private val _mountains = MutableStateFlow(emptyList<Mountain>())
val mountains: StateFlow<List<Mountain>> = _mountains
private var loaded = false
/**
* Loads the list of mountains from the list of mountains from the raw resource.
*/
suspend fun loadMountains(): StateFlow<List<Mountain>> {
if (!loaded) {
loaded = true
_mountains.value = withContext(Dispatchers.IO) {
context.resources.openRawResource(R.raw.top_peaks).use { inputStream ->
readMountains(inputStream)
}
}
}
return mountains
}
/**
* Reads the [Waypoint]s from the given [inputStream] and returns a list of [Mountain]s.
*/
private fun readMountains(inputStream: InputStream) =
readWaypoints(inputStream).mapIndexed { index, waypoint ->
waypoint.toMountain(index)
}.toList()
/**
* Class for collecting data fields and creating a valid [Waypoint] or null if any required data
* is invalid or missing.
*/
private data class WaypointBuilder(
var latitude: Double? = null,
var longitude: Double? = null,
var name: String? = null,
var elevation: Double? = null,
) {
fun build(): Waypoint? {
val latitude = latitude ?: return null
val longitude = longitude ?: return null
val elevation = elevation ?: return null
val name = name ?: return null
return Waypoint(
name = name,
location = LatLng(latitude, longitude),
elevationMeters = elevation,
)
}
}
/**
* Read all of the waypoints from a GPX file.
*/
private fun readWaypoints(inputStream: InputStream): Sequence<Waypoint> = sequence {
// We don't use namespaces
val ns: String? = null
val parser = Xml.newPullParser()
parser.setInput(inputStream, null)
try {
var eventType = parser.eventType
var builder: WaypointBuilder? = null
while (eventType != XmlPullParser.END_DOCUMENT) {
when (eventType) {
XmlPullParser.START_TAG -> {
if (parser.name == "wpt") {
builder = WaypointBuilder(
latitude = parser.getAttributeValue(ns, "lat").toDouble(),
longitude = parser.getAttributeValue(ns, "lon").toDouble(),
)
} else if (builder != null) {
when (parser.name) {
"name" -> builder.name = parser.nextText()
"ele" -> builder.elevation = parser.nextText().toDouble()
}
}
}
XmlPullParser.END_TAG -> {
if (parser.name == "wpt" && builder != null) {
builder.build()?.let { waypoint -> yield(waypoint) }
builder = null
}
}
}
eventType = parser.next()
}
} catch (e: XmlPullParserException) {
// Handle parsing errors
} catch (e: IOException) {
// Handle IO errors
}
}
}
private data class Waypoint(
val name: String,
val location: LatLng,
val elevationMeters: Double,
)
private fun Waypoint.toMountain(id: Int): Mountain {
return Mountain(
id = id,
name = name,
location = location,
elevation = elevationMeters.meters
)
}