-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathTimedSheetManager.kt
More file actions
82 lines (70 loc) · 2.64 KB
/
TimedSheetManager.kt
File metadata and controls
82 lines (70 loc) · 2.64 KB
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
package to.bitkit.utils.timedsheets
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Job
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.launch
import to.bitkit.ui.components.TimedSheetType
import to.bitkit.utils.Logger
class TimedSheetManager(private val scope: CoroutineScope) {
private val _currentSheet = MutableStateFlow<TimedSheetType?>(null)
val currentSheet: StateFlow<TimedSheetType?> = _currentSheet.asStateFlow()
private val registeredSheets = mutableListOf<TimedSheetItem>()
private var currentTimedSheet: TimedSheetItem? = null
private var checkJob: Job? = null
fun registerSheet(sheet: TimedSheetItem) {
registeredSheets.add(sheet)
registeredSheets.sortByDescending { it.priority }
Logger.debug(
"Registered timed sheet: ${sheet.type.name} with priority: ${sheet.priority}",
context = TAG
)
}
fun onHomeScreenEntered() {
Logger.debug("User entered home screen, starting timer", context = TAG)
checkJob?.cancel()
checkJob = scope.launch {
delay(CHECK_DELAY_MILLIS)
checkAndShowNextSheet()
}
}
fun onHomeScreenExited() {
Logger.debug("User exited home screen, cancelling timer", context = TAG)
checkJob?.cancel()
checkJob = null
}
fun dismissCurrentSheet() {
if (currentTimedSheet == null) return
scope.launch {
currentTimedSheet?.onDismissed()
_currentSheet.value = null
currentTimedSheet = null
Logger.debug("Clearing timed sheet queue", context = TAG)
}
}
private suspend fun checkAndShowNextSheet() {
Logger.debug("Registered sheets: ${registeredSheets.map { it.type.name }}")
for (sheet in registeredSheets.toList()) {
if (sheet.shouldShow()) {
Logger.debug(
"Showing timed sheet: ${sheet.type.name} with priority: ${sheet.priority}",
context = TAG
)
currentTimedSheet = sheet
_currentSheet.value = sheet.type
sheet.onShown()
registeredSheets.remove(sheet)
return
}
}
Logger.debug("No timed sheets need to be shown", context = TAG)
_currentSheet.value = null
currentTimedSheet = null
}
companion object {
private const val TAG = "TimedSheetManager"
private const val CHECK_DELAY_MILLIS = 2000L
}
}