aboutsummaryrefslogtreecommitdiff
path: root/app/src/main/kotlin/com/pitchedapps/frost/utils/Prefs.kt
blob: d99e8417d3fdc20cc9a1a283bbc4468651e91e01 (plain)
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
package com.pitchedapps.frost.utils

import android.content.Context
import android.content.SharedPreferences

/**
 * Created by Allan Wang on 2017-05-28.
 *
 * Shared Preference object with lazy cached retrievals
 */

private val PREFERENCE_NAME = "${com.pitchedapps.frost.BuildConfig.APPLICATION_ID}.prefs"
private val LAST_ACTIVE = "last_active"
private val USER_ID = "user_id"

object Prefs {

    private const val prefDefaultLong = -2L

    lateinit private var c: Context
    operator fun invoke(c: Context) {
        this.c = c
        lastActive = 0
    }

    private val sp: SharedPreferences by lazy { c.getSharedPreferences(PREFERENCE_NAME, Context.MODE_PRIVATE) }

    var lastActive: Long = prefDefaultLong
        get() {
            if (field == prefDefaultLong) field = sp.getLong(LAST_ACTIVE, -1)
            return field
        }
        set(value) {
            field = value
            if (value != prefDefaultLong) set(LAST_ACTIVE, System.currentTimeMillis())
        }

    const val userIdDefault = -1L
    var userId: Long = prefDefaultLong
        get() {
            if (field == prefDefaultLong) field = sp.getLong(USER_ID, userIdDefault)
            return field
        }
        set(value) {
            field = value
            if (value != prefDefaultLong) set(USER_ID, value)
        }

    private fun set(key: String, value: Boolean) = sp.edit().putBoolean(key, value).apply()
    private fun set(key: String, value: Int) = sp.edit().putInt(key, value).apply()
    private fun set(key: String, value: Long) = sp.edit().putLong(key, value).apply()
    private fun set(key: String, value: String) = sp.edit().putString(key, value).apply()

    fun clear() {
        L.d("Clearing Prefs")
        sp.edit().clear().apply()
        lastActive = prefDefaultLong
        userId = prefDefaultLong
    }
}