aboutsummaryrefslogtreecommitdiff
path: root/app/src/main/java/moe/yuuta/workmode/suspend/data/SuspendedStorage.kt
blob: a6c6cddf61cfbe013bec277a22a7aa90be9e74f9 (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
61
62
63
64
65
66
67
68
package moe.yuuta.workmode.suspend.data

import android.content.Context
import android.content.SharedPreferences
import com.elvishew.xlog.XLog
import moe.yuuta.workmode.utils.Utils
import java.util.stream.Collectors

/**
 * An independent storage of suspended status
 */
class SuspendedStorage(private val mContext: Context) {
    private val logger = XLog.tag("Storage").build()

    fun getStorage(): SharedPreferences = mContext.getSharedPreferences("suspended", Context.MODE_PRIVATE)

    fun getList(): List<String> = (getStorage().getStringSet("list", setOf()) ?: listOf<String>()).toList()

    fun setList(set: Set<String>) {
        logger.d("s() $set")
        getStorage().edit().putStringSet("list", set).apply()
    }

    fun setStatus(status: Status) {
        getStorage().edit().putInt("status",
                when (status) {
                    Status.OFF -> 0
                    Status.ON -> 1
                }).apply()
    }

    fun getStatus(): Status =
            when (getStorage().getInt("status", 0)) {
                0 -> Status.OFF
                1 -> Status.ON
                else -> Status.OFF
            }

    fun setListMode(listMode: ListMode) {
        getStorage().edit().putInt("list_mode",
                when (listMode) {
                    ListMode.BLACKLIST -> 0
                    ListMode.WHITELIST -> 1
                }).apply()
    }

    fun getListMode(): ListMode =
            when (getStorage().getInt("list_mode", 0)) {
                0 -> ListMode.BLACKLIST
                1 -> ListMode.WHITELIST
                else -> ListMode.BLACKLIST
            }

    fun cleanList(context: Context) {
        val installed = mContext.packageManager.getInstalledApplications(0)
                .stream()
                .filter(Utils.buildGeneralApplicationInfoFilter(context))
                .map {
                    return@map it.packageName
                }
                .collect(Collectors.toList())
        setList(getList().stream()
                .filter {
                    return@filter installed.contains(it)
                }
                .collect(Collectors.toSet()))
    }
}