package org.opentracker import android.content.Context import android.content.SharedPreferences import kotlin.properties.ReadWriteProperty import kotlin.reflect.KProperty /** Everything the app keeps. The service reads it on every start, because a restarted sticky service gets no Intent. */ class Prefs(context: Context) { val raw: SharedPreferences = context.getSharedPreferences("ot", Context.MODE_PRIVATE) // The property name is the stored key. Renaming a property loses the setting on existing installs. var url by string() var token by string() var tracking by boolean() /** The secret behind a pairing challenge, until the browser returns with a code. */ var pairVerifier by string() /** A [Mode] name. */ var mode by string() var lastUploadMs by long() var queued by long() var error by string() /** The mode in the user's language. */ fun modeLabel(context: Context): String? = when (mode) { Mode.VEHICLE.name -> context.getString(R.string.mode_vehicle) Mode.WALK.name -> context.getString(R.string.mode_walk) Mode.DWELL.name -> context.getString(R.string.mode_dwell) Mode.STATIONARY.name -> context.getString(R.string.mode_stationary) else -> null } fun asked(step: String): Boolean = raw.getBoolean("asked $step", false) fun markAsked(step: String) = raw.edit().putBoolean("asked $step", true).apply() private fun string() = pref({ getString(it, null) }, { k, v: String? -> putString(k, v) }) private fun long() = pref({ getLong(it, 0) }, { k, v: Long -> putLong(k, v) }) private fun boolean() = pref({ getBoolean(it, false) }, { k, v: Boolean -> putBoolean(k, v) }) private fun pref(get: SharedPreferences.(String) -> T, put: SharedPreferences.Editor.(String, T) -> Unit) = object : ReadWriteProperty { override fun getValue(thisRef: Any?, property: KProperty<*>): T = raw.get(property.name) override fun setValue(thisRef: Any?, property: KProperty<*>, value: T) = raw.edit().apply { put(property.name, value) }.apply() } }