@@ -10,13 +10,15 @@ import kotlinx.coroutines.flow.MutableStateFlow
1010import kotlinx.coroutines.flow.StateFlow
1111import kotlinx.coroutines.flow.asStateFlow
1212import kotlinx.coroutines.launch
13+ import kotlinx.datetime.Clock
1314import kotlinx.serialization.json.Json
1415import neth.iecal.trease.models.FocusStats
1516import neth.iecal.trease.models.TimerStatus
1617import neth.iecal.trease.models.TreeData
1718import neth.iecal.trease.onForceStopFocus
1819import neth.iecal.trease.utils.CacheManager
1920import neth.iecal.trease.utils.CoinManager
21+ import neth.iecal.trease.utils.FocusStateManager
2022import neth.iecal.trease.utils.TreeStatsLodger
2123import neth.iecal.trease.utils.randomBiased
2224import kotlin.math.log2
@@ -65,10 +67,23 @@ class HomeScreenViewModel : ViewModel() {
6567 val currentTreeSeedVariant : StateFlow <Int > = _currentTreeSeedVariant .asStateFlow()
6668
6769 var treeList : MutableStateFlow <List <TreeData >> = MutableStateFlow (emptyList())
70+
71+ // caches the state if tree is growing or not along so if accidentally system kills the app, user can restart from last progress
72+ val focusStateManager = FocusStateManager ()
6873 init {
6974 viewModelCoroutineScope.launch {
7075 coins.value = coinManager.reloadCoins()
7176 reloadTreeList()
77+
78+ val runDuration = focusStateManager.isRunning()
79+ if (runDuration!= null ){
80+ val isNotOver = runDuration > Clock .System .now().epochSeconds
81+ if (isNotOver){
82+ val treeInfo = focusStateManager.getRunningTree()!!
83+ treeInfo.duration - = (runDuration - Clock .System .now().epochSeconds)
84+ selectWitheredTree(treeInfo)
85+ }
86+ }
7287 }
7388 }
7489 suspend fun reloadTreeList (){
@@ -136,6 +151,13 @@ class HomeScreenViewModel : ViewModel() {
136151 // We use the current remaining seconds as the "start line" for progress
137152 val initialSecondsAtStart = _remainingSeconds .value
138153 timerJob = viewModelScope.launch {
154+ focusStateManager.setRunning(Clock .System .now().epochSeconds + _remainingSeconds .value)
155+ focusStateManager.setRunningTree(FocusStats (
156+ selectedMinutes.value* 60 ,
157+ selectedTree.value.id,
158+ false ,
159+ treeSeed = currentTreeSeedVariant.value,
160+ ))
139161 while (_remainingSeconds .value > 0 ) {
140162 delay(1000 )
141163 _remainingSeconds .value - = 1
@@ -211,6 +233,7 @@ class HomeScreenViewModel : ViewModel() {
211233 )
212234 coins.value = coinManager.reloadCoins()
213235 }
236+ focusStateManager.setRunning(- 1 )
214237 }
215238
216239 }
0 commit comments