Bimba.git

ref: v2.1

app/src/main/java/ml/adamsprogs/bimba/models/Favourite.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
package ml.adamsprogs.bimba.models

import android.content.Context
import android.os.Parcel
import android.os.Parcelable
import ml.adamsprogs.bimba.ProviderProxy
import ml.adamsprogs.bimba.safeSplit
import java.io.File
import java.math.BigInteger
import java.security.SecureRandom
import kotlin.collections.*

class Favourite : Parcelable, ProviderProxy.OnDeparturesReadyListener {
    private val cacheDir: File
    private lateinit var listener: ProviderProxy.OnDeparturesReadyListener
    var name: String
        private set
    var segments: HashSet<StopSegment>
        private set
    private var fullDepartures: Map<String, List<Departure>> = HashMap()
    private val cache = HashMap<Plate.ID, List<Departure>>()
    private var listenerId = ""

    val size
        get() = segments.sumBy {
            it.size
        }

    private val providerProxy: ProviderProxy

    constructor(parcel: Parcel) {
        this.name = parcel.readString()!!
        @Suppress("UNCHECKED_CAST")
        val set = HashSet<StopSegment>()
        val array = parcel.readParcelableArray(StopSegment::class.java.classLoader)!!
        array.forEach {
            set.add(it as StopSegment)
        }
        this.segments = set
        this.cacheDir = File(parcel.readString())
        val mapDir = File(parcel.readString())

        val mapString = mapDir.readText()

        val map = HashMap<String, List<Departure>>()
        mapString.safeSplit("%")!!.forEach { it ->
            val (k, v) = it.split("#")
            map[k] = v.split("&").map { Departure.fromString(it) }
        }
        this.fullDepartures = map
        mapDir.delete()
        providerProxy = ProviderProxy()
    }

    constructor(name: String, segments: HashSet<StopSegment>, cache: Map<String, List<Departure>>, context: Context) {
        this.fullDepartures = cache
        this.name = name
        this.segments = segments
        this.cacheDir = context.cacheDir
        providerProxy = ProviderProxy(context)
    }

    constructor(name: String, timetables: HashSet<StopSegment>, context: Context) {
        this.name = name
        this.segments = timetables
        this.cacheDir = context.cacheDir
        providerProxy = ProviderProxy(context)

    }

    override fun describeContents(): Int {
        return Parcelable.CONTENTS_FILE_DESCRIPTOR
    }

    override fun writeToParcel(dest: Parcel?, flags: Int) {
        dest?.writeString(name)
        val parcelableSegments = segments.map { it }.toTypedArray()
        dest?.writeParcelableArray(parcelableSegments, flags)
        dest?.writeString(cacheDir.absolutePath)

        val bytes = ByteArray(4) { 0 }
        SecureRandom().nextBytes(bytes)
        val mapFile = File(cacheDir, BigInteger(1, bytes).toString(16))
        dest?.writeString(mapFile.absolutePath)

        var isFirst = true
        var map = ""
        fullDepartures.forEach { it ->
            if (isFirst)
                isFirst = false
            else
                map += '%'

            map += "${it.key}#${it.value.joinToString("&") { it.toString() }}"
        }
        mapFile.writeText(map)
    }

    fun delete(plateId: Plate.ID): Boolean {
        segments.forEach {
            if (!it.remove(plateId))
                return false
        }
        removeFromCache(plateId)
        return true
    }

    fun rename(newName: String) {
        name = newName
    }

    companion object CREATOR : Parcelable.Creator<Favourite> {
        override fun createFromParcel(parcel: Parcel): Favourite {
            return Favourite(parcel)
        }

        override fun newArray(size: Int): Array<Favourite?> {
            return arrayOfNulls(size)
        }
    }

    fun nextDeparture() =
            if (cache.isEmpty())
                null
            else
                cache.flatMap { it.value }.let { it ->
                    if (it.isEmpty())
                        null
                    else
                        it.sortedBy { it.time }[0]
                }


    fun fullTimetable(): Map<String, List<Departure>> {
        if (fullDepartures.isEmpty())
            fullDepartures = providerProxy.getFullTimetable(segments)
        return fullDepartures
    }

    private fun removeFromCache(plate: Plate.ID) {
        val map = HashMap<String, List<Departure>>()
        fullDepartures
        fullDepartures.forEach { it ->
            map[it.key] = it.value.filter { plate.line != it.line || plate.headsign != it.headsign }
        }
        fullDepartures = map
    }

    fun subscribeForDepartures(listener: ProviderProxy.OnDeparturesReadyListener, context: Context): String {
        this.listener = listener
        listenerId = providerProxy.subscribeForDepartures(segments, this, context)
        return listenerId
    }

    override fun onDeparturesReady(departures: List<Departure>, plateId: Plate.ID?, code: Int) {
        if (plateId == null) {
            cache.clear()
            cache[Plate.ID.dummy] = departures
        } else {
            cache.remove(Plate.ID.dummy)
            cache[plateId] = departures
        }
        listener.onDeparturesReady(departures, plateId, code)
    }

    fun unsubscribeFromDepartures(context: Context) {
        providerProxy.unsubscribeFromDepartures(listenerId, context)
    }
}