Bimba.git

ref: 684a5b38ec0977ecaf2bd1d06f701061d14e7e02

app/src/main/java/ml/adamsprogs/bimba/models/Timetable.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
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
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
package ml.adamsprogs.bimba.models

import android.annotation.SuppressLint
import android.content.Context
import android.database.*
import android.database.sqlite.SQLiteDatabase
import ml.adamsprogs.bimba.*
import ml.adamsprogs.bimba.models.gtfs.*
import ml.adamsprogs.bimba.models.suggestions.*
import java.io.*
import kotlin.collections.*
import java.util.Calendar as JCalendar

class Timetable private constructor() {
    companion object {
        private var timetable: Timetable? = null

        fun getTimetable(context: Context? = null, force: Boolean = false): Timetable {
            return if (timetable == null || force)
                if (context != null) {
                    constructTimetable(context)
                    timetable!!
                } else
                    throw IllegalArgumentException("new timetable requested and no `context` given")
            else if (context != null) {
                try {
                    constructTimetable(context)
                    timetable!!
                } catch (e: Exception) {
                    timetable!!
                }
            } else
                timetable!!
        }

        private fun constructTimetable(context: Context) {
            val timetable = Timetable()
            val filesDir = context.getSecondaryExternalFilesDir()
            val dbFile = File(filesDir, "timetable.db")
            timetable.db = SQLiteDatabase.openDatabase(dbFile.path, null, SQLiteDatabase.OPEN_READONLY)
            this.timetable = timetable
        }
    }

    private lateinit var db: SQLiteDatabase
    private var _stops: List<StopSuggestion>? = null

    fun refresh() {
    }

    fun getStopSuggestions(context: Context, force: Boolean = false): List<StopSuggestion> {
        if (_stops != null && !force)
            return _stops!!

        val ids = HashMap<String, HashSet<AgencyAndId>>()
        val zones = HashMap<String, String>()

        val cursor = db.rawQuery("select stop_name, stop_id, zone_id from stops", null)

        while (cursor.moveToNext()) {
            val name = cursor.getString(0)
            val id = cursor.getInt(1)
            val zone = cursor.getString(2)
            if (name !in ids)
                ids[name] = HashSet()
            ids[name]!!.add(AgencyAndId(id.toString()))
            zones[name] = zone
        }

        cursor.close()

        _stops = ids.map {
            val colour = when (zones[it.key]) {
                "A" -> "#${getColour(R.color.zoneA, context).toString(16)}"
                "B" -> "#${getColour(R.color.zoneB, context).toString(16)}"
                "C" -> "#${getColour(R.color.zoneC, context).toString(16)}"
                else -> "#000000"
            }
            StopSuggestion(it.key, it.value, zones[it.key]!!, colour)
        }.sorted()
        return _stops!!
    }

    fun getLineSuggestions(): List<LineSuggestion> {
        val routes = ArrayList<LineSuggestion>()
        val cursor = db.rawQuery("select * from routes", null)

        while (cursor.moveToNext()) {
            val routeId = cursor.getString(0)

            routes.add(LineSuggestion(routeId,
                    createRouteFromCursorRow(cursor)))
        }

        return routes.sortedBy { it.name }
    }

    fun getHeadlinesForStop(stops: Set<AgencyAndId>): Map<AgencyAndId, Pair<String, Set<String>>> {
        val headsigns = HashMap<AgencyAndId, Pair<String, HashSet<String>>>()

        val stopsIndex = HashMap<Int, String>()
        val where = stops.joinToString(" or ", "where ") { "stop_id = ?" }
        var cursor = db.rawQuery("select stop_id, stop_code from stops $where", stops.map { it.toString() }.toTypedArray())

        while (cursor.moveToNext()) {
            stopsIndex[cursor.getInt(0)] = cursor.getString(1)
        }

        cursor.close()

        cursor = db.rawQuery("select stop_id, route_id, trip_headsign " +
                "from stop_times natural join trips " +
                where, stops.map { it.toString() }.toTypedArray())

        while (cursor.moveToNext()) {
            val stop = cursor.getInt(0)
            val stopId = AgencyAndId(stop.toString())
            val route = cursor.getString(1)
            val headsign = cursor.getString(2)
            if (stopId !in headsigns)
                headsigns[stopId] = Pair(stopsIndex[stop]!!, HashSet())
            headsigns[stopId]!!.second.add("$route$headsign")
        }

        cursor.close()

        return headsigns

        /*
        1435 -> (AWF03, {232 → Os. Rusa})
        1436 -> (AWF04, {232 → Rondo Kaponiera})
        1437 -> (AWF02, {76 → Pl. Bernardyński, 74 → Os. Sobieskiego, 603 → Pl. Bernardyński})
        1634 -> (AWF01, {76 → Os. Dębina, 603 → Łęczyca/Dworcowa})
        171 -> (AWF42, {29 → Pl. Wiosny Ludów})
        172 -> (AWF41, {10 → Połabska, 29 → Dębiec, 15 → Budziszyńska, 10 → Dębiec, 15 → Os. Sobieskiego, 12 → Os. Sobieskiego, 6 → Junikowo, 18 → Ogrody, 2 → Ogrody})
        4586 -> (AWF73, {10 → Franowo, 29 → Franowo, 6 → Miłostowo, 5 → Stomil, 18 → Franowo, 15 → Franowo, 12 → Starołęka, 74 → Os. Orła Białego})
        */
    }

    fun getStopName(stopId: AgencyAndId): String {
        val cursor = db.rawQuery("select stop_name from stops where stop_id = ?",
                arrayOf(stopId.id))
        cursor.moveToNext()
        val name = cursor.getString(0)
        cursor.close()

        return name
    }

    fun getStopCode(stopId: AgencyAndId): String {
        val cursor = db.rawQuery("select stop_code from stops where stop_id = ?",
                arrayOf(stopId.id))
        cursor.moveToNext()
        val code = cursor.getString(0)
        cursor.close()

        return code
    }

    fun getStopDepartures(stopId: AgencyAndId): Map<AgencyAndId, List<Departure>> {
        val map = HashMap<AgencyAndId, ArrayList<Departure>>()
        val cursor = db.rawQuery("select route_id, service_id, departure_time, " +
                "wheelchair_accessible, stop_sequence, trip_id, trip_headsign, route_desc " +
                "from stop_times natural join trips natural join routes where stop_id = ?",
                arrayOf(stopId.id))

        while (cursor.moveToNext()) {
            val line = AgencyAndId(cursor.getString(0))
            val service = AgencyAndId(cursor.getInt(1).toString())
            val mode = calendarToMode(service)
            val time = parseTime(cursor.getString(2))
            val lowFloor = cursor.getInt(3) == 1
            val stopSequence = cursor.getInt(4)
            val tripId = createTripId(cursor.getString(5))
            val headsign = cursor.getString(6)
            val desc = cursor.getString(7)

            val modifications = Route.createModifications(desc)

            val modification = explainModification(tripId, stopSequence, modifications)
            val departure = Departure(line, mode, time, lowFloor, modification, headsign)
            if (map[service] == null)
                map[service] = ArrayList()
            map[service]!!.add(departure)
        }

        cursor.close()
        map.forEach { it.value.sortBy { it.time } }

        return map
    }

    fun getStopDeparturesBySegments(segments: HashSet<StopSegment>): Map<AgencyAndId, List<Departure>> {
        val wheres = segments.flatMap {
            it.plates?.map {
                "(stop_id = ${it.stop} and route_id = '${it.line}' and trip_headsign = '${it.headsign}')"
            } ?: listOf()
        }.joinToString(" or ")

        val cursor = db.rawQuery("select route_id, service_id, departure_time, " +
                "wheelchair_accessible, stop_sequence, trip_id, trip_headsign, route_desc " +
                "from stop_times natural join trips natural join routes where $wheres", null)

        val map = parseDeparturesCursor(cursor)
        cursor.close()
        return map
    }

    private fun parseDeparturesCursor(cursor: Cursor): Map<AgencyAndId, List<Departure>> {
        val map = HashMap<AgencyAndId, ArrayList<Departure>>()

        while (cursor.moveToNext()) {
            val line = AgencyAndId(cursor.getString(0))
            val service = AgencyAndId(cursor.getInt(1).toString())
            val mode = calendarToMode(service)
            val time = parseTime(cursor.getString(2))
            val lowFloor = cursor.getInt(3) == 1
            val stopSequence = cursor.getInt(4)
            val tripId = createTripId(cursor.getString(5))
            val headsign = cursor.getString(6)
            val desc = cursor.getString(7)

            val modifications = Route.createModifications(desc)

            val modification = explainModification(tripId, stopSequence, modifications)
            val departure = Departure(line, mode, time, lowFloor, modification, headsign)
            if (map[service] == null)
                map[service] = ArrayList()
            map[service]!!.add(departure)
        }

        map.forEach { it.value.sortBy { it.time } }
        return map
    }


    private fun parseTime(time: String): Int {
        val cal = JCalendar.getInstance()
        val (h, m, s) = time.split(":")
        cal.set(JCalendar.HOUR_OF_DAY, h.toInt())
        cal.set(JCalendar.MINUTE, m.toInt())
        cal.set(JCalendar.SECOND, s.toInt())
        return cal.secondsAfterMidnight()
    }

    fun calendarToMode(serviceId: AgencyAndId): List<Int> {
        val days = ArrayList<Int>()
        val cursor = db.rawQuery("select * from calendar where service_id = ?",
                arrayOf(serviceId.id))

        cursor.moveToNext()
        (1 until 7).forEach {
            if (cursor.getInt(it) == 1) days.add(it - 1)
        }

        cursor.close()
        return days
    }

    private fun explainModification(tripId: Trip.ID, stopSequence: Int, routeModifications: Map<String, String>): List<String> { //todo<p:1> "kurs obsługiwany taborem niskopodłogowym" -> ignore
        val explanations = ArrayList<String>()
        tripId.modification.forEach {
            if (it.stopRange != null) {
                if (stopSequence in it.stopRange)
                    explanations.add(routeModifications[it.id.id]!!)
            } else {
                explanations.add(routeModifications[it.id.id]!!)
            }
        }

        return explanations
    }

    private fun createRouteFromCursorRow(cursor: Cursor): Route {
        val routeId = cursor.getString(0)
        val agencyId = cursor.getInt(1).toString()
        val shortName = cursor.getString(2)
        val longName = cursor.getString(3)
        val desc = cursor.getString(4)
        val type = cursor.getInt(5)
        val colour = cursor.getString(6).toInt(16)
        val textColour = cursor.getString(7).toInt(16)

        return Route.create(routeId, agencyId, shortName, longName, desc, type, colour, textColour)
    }

    private fun createTripId(rawId: String): Trip.ID {
        if (rawId.contains('^')) {
            var modification = rawId.split("^")[1]
            val isMain = modification[modification.length - 1] == '+'
            if (isMain)
                modification = modification.subSequence(0, modification.length - 1) as String
            val modifications = HashSet<Trip.ID.Modification>()
            if (modification != "") {
                modification.split(",").forEach {
                    try {
                        val (id, start, end) = it.split(":")
                        modifications.add(Trip.ID.Modification(AgencyAndId(id), IntRange(start.toInt(), end.toInt())))
                    } catch (e: Exception) {
                        modifications.add(Trip.ID.Modification(AgencyAndId(it), null))
                    }
                }
            }
            return Trip.ID(rawId, AgencyAndId(rawId.split("^")[0]), modifications, isMain)
        } else
            return Trip.ID(rawId, AgencyAndId(rawId), HashSet(), false)
    }

    @SuppressLint("Recycle")
    fun isEmpty(): Boolean {
        var result: Boolean
        var cursor: Cursor? = null
        try {
            cursor = db.rawQuery("select * from feed_info", null)
            result = !cursor.moveToNext()
        } catch (e: Exception) {
            result = true
        } finally {
            cursor?.close()
        }
        return result
    }

    fun getValidSince(): String {
        val cursor = db.rawQuery("select feed_start_date from feed_info", null)

        cursor.moveToNext()
        val validTill = cursor.getString(0)

        cursor.close()
        return validTill
    }

    fun getValidTill(): String {
        val cursor = db.rawQuery("select feed_end_date from feed_info", null)

        cursor.moveToNext()
        val validTill = cursor.getString(0)

        cursor.close()
        return validTill
    }

    fun getServiceForToday(): AgencyAndId {
        val today = JCalendar.getInstance().get(JCalendar.DAY_OF_WEEK)
        return getServiceFor(today)
    }

    fun getServiceForTomorrow(): AgencyAndId {
        val tomorrow = JCalendar.getInstance()
        tomorrow.add(JCalendar.DAY_OF_MONTH, 1)
        val tomorrowDoW = tomorrow.get(JCalendar.DAY_OF_WEEK)
        return getServiceFor(tomorrowDoW)
    }

    fun getServiceFor(day: Int): AgencyAndId {
        val dayColumn = arrayOf("monday", "tuesday", "wednesday", "thursday", "friday", "saturday", "sunday")[((day + 5) % 7)]
        val cursor = db.rawQuery("select service_id from calendar where $dayColumn = 1", null)

        val service: Int
        cursor.moveToNext()
        try {
            service = cursor.getInt(0)
            cursor.close()
            return AgencyAndId(service.toString())
        } catch (e: CursorIndexOutOfBoundsException) {
            throw IllegalArgumentException()
        }
    }

    fun getPlatesForStop(stop: AgencyAndId): Set<Plate.ID> {
        val plates = HashSet<Plate.ID>()
        val cursor = db.rawQuery("select route_id, trip_headsign " +
                "from stop_times natural join trips where stop_id = ? " +
                "group by route_id, trip_headsign", arrayOf(stop.id))

        while (cursor.moveToNext()) {
            val routeId = AgencyAndId(cursor.getString(0))
            val headsign = cursor.getString(1)
            plates.add(Plate.ID(routeId, stop, headsign))
        }

        cursor.close()
        return plates
    }

    fun getTripGraphs(id: AgencyAndId): Array<TripGraph> {
        val graphs = arrayOf(TripGraph(), TripGraph())

        val cursor = db.rawQuery("select trip_id, trip_headsign, direction_id, stop_id, " +
                "stop_sequence, pickup_type, stop_name, zone_id " +
                "from stop_times natural join trips natural join stops" +
                "where route_id = ?", arrayOf(id.id))

        while (cursor.moveToNext()) {
            val trip = cursor.getString(0)
            val headsign = cursor.getString(1)
            val direction = cursor.getInt(2)
            val stopId = cursor.getInt(3)
            val sequence = cursor.getInt(4)
            val pickupType = cursor.getInt(5)
            val stopName = cursor.getString(6)
            val zone = cursor.getString(7)

            if (trip.contains('+')) {
                graphs[direction].mainTrip[stopId] = sequence
                graphs[direction].headsign = headsign
            }

            if (graphs[direction].otherTrips[trip] == null)
                graphs[direction].otherTrips[trip] = HashMap()
            graphs[direction].otherTrips[trip]?.put(sequence, Stop(stopId, null, stopName, null, null, zone[0], pickupType == 3))
        }

        cursor.close()

        graphs.forEach {
            val thisTripGraph = it
            it.otherTrips.forEach {
                val tripId = it.key
                val trip = it.value
                it.value.keys.sortedBy { it }.forEach {
                    if (thisTripGraph.tripsMetadata[tripId] == "" || thisTripGraph.tripsMetadata[tripId] == "o")
                        if (thisTripGraph.mainTrip[trip[it]!!.id] != null) {
                            val mainLayer = thisTripGraph.mainTrip[trip[it]!!.id]!!
                            if (it == 0 || thisTripGraph.tripsMetadata[tripId]!![0] == 'o') {
                                thisTripGraph.tripsMetadata[tripId] = "o|$mainLayer|$it"
                            } else {
                                val startingLayer = mainLayer - it + 1
                                thisTripGraph.tripsMetadata[tripId] = "i|$startingLayer|$it"
                            }
                        }
                }
            }
        }

        return graphs
    }

    class TripGraph {
        var headsign = ""
        val mainTrip = HashMap<Int, Int>()
        val otherTrips = HashMap<String, HashMap<Int, Stop>>()
        val tripsMetadata = HashMap<String, String>()
    }
}