-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTimerViewModel.kt
More file actions
710 lines (640 loc) · 28 KB
/
TimerViewModel.kt
File metadata and controls
710 lines (640 loc) · 28 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
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
@file:OptIn(ExperimentalTime::class)
package net.solvetheriddle.roundtimer.viewmodel
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import kotlin.time.Clock
import kotlin.random.Random
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 kotlinx.datetime.LocalDateTime
import kotlinx.datetime.TimeZone
import kotlinx.datetime.format.DayOfWeekNames
import kotlinx.datetime.format.MonthNames
import kotlinx.datetime.format.Padding
import kotlinx.datetime.format.char
import kotlinx.datetime.toLocalDateTime
import net.solvetheriddle.roundtimer.audio.AudioScheduler
import net.solvetheriddle.roundtimer.model.AudioCue
import net.solvetheriddle.roundtimer.model.AudioPattern
import net.solvetheriddle.roundtimer.model.Game
import net.solvetheriddle.roundtimer.model.ScheduledSound
import net.solvetheriddle.roundtimer.model.Sound
import net.solvetheriddle.roundtimer.model.Round
import net.solvetheriddle.roundtimer.model.TimerState
import net.solvetheriddle.roundtimer.platform.getScreenLocker
import net.solvetheriddle.roundtimer.platform.getSoundPlayer
import net.solvetheriddle.roundtimer.platform.getAnalyticsService
import net.solvetheriddle.roundtimer.storage.RoundTimerStorage
import net.solvetheriddle.roundtimer.storage.createPlatformStorage
import kotlin.time.ExperimentalTime
import kotlin.time.TimeSource
private const val UPDATE_INTERVAL = 50L
class TimerViewModel : ViewModel() {
private val storage by lazy {
RoundTimerStorage(createPlatformStorage())
}
private val soundPlayer by lazy { getSoundPlayer() }
private val screenLocker by lazy { getScreenLocker() }
private val analyticsService by lazy { getAnalyticsService() }
private val audioScheduler by lazy { AudioScheduler(soundPlayer, viewModelScope) }
private val _state = MutableStateFlow(TimerState())
val state: StateFlow<TimerState> = _state.asStateFlow()
init {
// Initialize storage and load saved data
try {
storage.initialize()
viewModelScope.launch {
try {
val savedRounds = storage.loadRounds()
val configuredTime = storage.loadConfiguredTime() ?: _state.value.configuredTime
val games = storage.loadGames().sortedByDescending { it.id }
val activeGameId = storage.loadActiveGameId() ?: games.firstOrNull()?.id
val savedSettings = storage.loadSettings() ?: _state.value.settings
_state.value = _state.value.copy(
rounds = savedRounds,
configuredTime = configuredTime,
currentTime = configuredTime,
games = games,
activeGameId = activeGameId,
settings = savedSettings,
// Load types from the active game
customTypes = games.find { it.id == activeGameId }?.customTypes ?: emptyList(),
playerTypes = games.find { it.id == activeGameId }?.playerTypes ?: emptyList(),
selectedPhase = "Setup",
selectedPlayer = "Everyone"
)
} catch (e: Exception) {
// Continue with empty list
}
}
} catch (e: Exception) {
// Continue with default state
}
}
private var timerJob: Job? = null
private var timerStartTime: TimeSource.Monotonic.ValueTimeMark? = null
private var initialTimerDuration: Long = 0L
private var fastForwardOffset: Long = 0L
private var deletedRound: Round? = null
private var deletedGame: Game? = null
fun updateConfiguredTime(seconds: Int) {
if (!_state.value.isRunning) {
val milliseconds = seconds * 1000L
// Update state
var currentState = _state.value.copy(
configuredTime = milliseconds,
currentTime = milliseconds
)
// Update active game configuration
val activeGameId = currentState.activeGameId
if (activeGameId != null) {
val updatedGames = currentState.games.map { game ->
if (game.id == activeGameId) {
val newConfigs = game.typeConfigurations.toMutableMap()
newConfigs[currentState.selectedPhase] = milliseconds
game.copy(typeConfigurations = newConfigs)
} else {
game
}
}
currentState = currentState.copy(games = updatedGames)
viewModelScope.launch {
storage.saveGames(updatedGames)
storage.saveConfiguredTime(milliseconds)
}
} else {
viewModelScope.launch {
storage.saveConfiguredTime(milliseconds)
}
}
_state.value = currentState
analyticsService.logEvent("configured_time_updated", mapOf("seconds" to seconds.toString()))
}
}
private fun getCurrentDate(): String {
val now = Clock.System.now()
val zone = TimeZone.currentSystemDefault()
val localDate = now.toLocalDateTime(zone)
val dateFormat = LocalDateTime.Format {
dayOfWeek(DayOfWeekNames.ENGLISH_FULL)
char(' ')
day(Padding.NONE)
char(' ')
monthName(MonthNames.ENGLISH_ABBREVIATED)
char(' ')
yearTwoDigits(2000)
}
return dateFormat.format(localDate)
}
fun startTimer() {
screenLocker.lock()
var currentState = _state.value
if (currentState.activeGameId == null) {
val newGame = Game(id = Clock.System.now().toEpochMilliseconds().toString(), date = getCurrentDate(), name = "")
val newGames = currentState.games + newGame
currentState = currentState.copy(games = newGames, activeGameId = newGame.id)
analyticsService.logEvent(
"game_created", mapOf("game_id" to newGame.id, "game_date" to newGame.date, "game_name" to newGame.name)
)
viewModelScope.launch {
storage.saveGames(newGames)
}
}
_state.value = currentState.copy(
isRunning = true,
currentTime = currentState.configuredTime,
overtimeTime = 0L,
isOvertime = false,
startTimestamp = Clock.System.now().toEpochMilliseconds()
)
analyticsService.logEvent(
"timer_started", mapOf(
"game_id" to (currentState.activeGameId ?: ""),
"configured_time" to currentState.configuredTime.toString(),
"subtle_drumming" to currentState.settings.isSubtleDrummingEnabled.toString(),
"intense_drumming" to currentState.settings.isIntenseDrummingEnabled.toString(),
"overtime_alarm" to currentState.settings.isOvertimeAlarmEnabled.toString(),
"timeout_gong" to currentState.settings.isTimeoutGongEnabled.toString(),
"jonas_scolding" to currentState.settings.isJonasScoldingEnabled.toString()
)
)
startCountdownWithPreciseAudio()
}
@OptIn(ExperimentalTime::class)
private fun startCountdownWithPreciseAudio() {
val configuredTime = _state.value.configuredTime
initialTimerDuration = configuredTime
timerStartTime = TimeSource.Monotonic.markNow()
fastForwardOffset = 0L
// Pre-calculate all scheduled audio events
val audioEvents = createAudioSchedule(configuredTime)
// Start the precise audio scheduler
audioScheduler.start(audioEvents)
// Start the UI update timer using the same time source
startSynchronizedCountdown()
}
private fun createAudioSchedule(timerDurationMs: Long): List<ScheduledSound> {
val events = mutableListOf<ScheduledSound>()
val audioCues = generateAudioCues()
audioCues.forEach { cue ->
val triggerTimeMs = timerDurationMs - (cue.threshold * 1000L)
if (triggerTimeMs >= 0) {
events.add(ScheduledSound(triggerTimeMs, cue.sound, cue.pattern))
}
}
// Add overtime sound schedule
val overtimeCues = createOvertimeSchedule(timerDurationMs)
events.addAll(overtimeCues)
return events.sortedBy { it.triggerTimeMs }
}
private fun generateAudioCues(): List<AudioCue> {
val settings = _state.value.settings
val audioCues = mutableListOf<AudioCue>()
if (settings.isSubtleDrummingEnabled) {
val subtleDrumRepeatCount = if (settings.isIntenseDrummingEnabled) 4 else 6
audioCues.add(
AudioCue(threshold = 60, sound = Sound.CALL, pattern = AudioPattern.Repeated(subtleDrumRepeatCount, 10 * 1000L))
)
}
if (settings.isIntenseDrummingEnabled) {
audioCues.add(
AudioCue(threshold = 21, sound = Sound.INTENSE)
)
}
if (settings.isTimeoutGongEnabled) {
audioCues.add(
AudioCue(threshold = 0, sound = Sound.TIMEOUT_GONG)
)
}
return audioCues
}
/**
* Creates a schedule of overtime sounds that play after the timer expires.
* You can customize this pattern based on your needs.
*/
private fun createOvertimeSchedule(timerDurationMs: Long): List<ScheduledSound> {
val overtimeEvents = mutableListOf<ScheduledSound>()
val settings = _state.value.settings
if (settings.isOvertimeAlarmEnabled) {
repeat(8) { seconds ->
val triggerTime = timerDurationMs + (seconds * 1000L)
overtimeEvents.add(ScheduledSound(triggerTime, Sound.OVERTIME))
}
for (seconds in 14 until 150 step 3) {
val triggerTime = timerDurationMs + (seconds * 800L)
overtimeEvents.add(ScheduledSound(triggerTime, Sound.OVERTIME))
}
}
if (settings.isJonasScoldingEnabled) {
val overtimeCalls = listOf(
Sound.OVERTIME_CALL1,
Sound.OVERTIME_CALL1,
Sound.OVERTIME_CALL2,
Sound.OVERTIME_CALL2,
Sound.OVERTIME_CALL3,
Sound.OVERTIME_CALL3,
Sound.OVERTIME_CALL4,
Sound.OVERTIME_CALL5,
Sound.OVERTIME_CALL6,
)
overtimeEvents.add(ScheduledSound(timerDurationMs + (8 * 1000L), overtimeCalls.random()))
overtimeEvents.add(ScheduledSound(timerDurationMs + (14 * 1000L), overtimeCalls.random()))
}
return overtimeEvents
}
@OptIn(ExperimentalTime::class)
private fun startSynchronizedCountdown() {
timerJob?.cancel()
timerJob = viewModelScope.launch {
while (_state.value.isRunning) {
delay(UPDATE_INTERVAL)
val currentState = _state.value
val elapsedTime = (timerStartTime?.elapsedNow()?.inWholeMilliseconds ?: 0L) + fastForwardOffset
if (elapsedTime < initialTimerDuration) {
// Normal countdown - calculate remaining time based on elapsed time
val remainingTime = maxOf(0L, initialTimerDuration - elapsedTime)
_state.value = currentState.copy(currentTime = remainingTime)
} else {
// Overtime mode - calculate overtime based on elapsed time
val overtimeTime = elapsedTime - initialTimerDuration
_state.value = currentState.copy(
currentTime = 0L,
isOvertime = true,
overtimeTime = overtimeTime
)
}
}
}
}
@OptIn(ExperimentalTime::class)
fun stopTimer() {
screenLocker.unlock()
timerJob?.cancel()
audioScheduler.stop()
val currentState = _state.value
if (currentState.isRunning) {
// Calculate elapsed time from configured time minus remaining time
val elapsedTime = (currentState.configuredTime - currentState.currentTime) / 1000 // Convert to seconds
val overtimeTime = currentState.overtimeTime / 1000 // Convert to seconds
// Save round to history
val newRound = Round(
id = uuid(),
duration = elapsedTime.toInt(),
overtime = overtimeTime.toInt(),
timestamp = Clock.System.now().toEpochMilliseconds(),
gameId = _state.value.activeGameId ?: "",
category = "${_state.value.selectedPhase} - ${_state.value.selectedPlayer}", // Legacy support
phase = _state.value.selectedPhase,
player = _state.value.selectedPlayer
)
val newRounds = currentState.rounds + newRound
_state.value = currentState.copy(
isRunning = false,
isOvertime = false,
currentTime = currentState.configuredTime,
overtimeTime = 0L,
rounds = newRounds
)
analyticsService.logEvent(
"timer_stopped", mapOf(
"game_id" to (currentState.activeGameId ?: ""),
"duration" to newRound.duration.toString(),
"overtime" to newRound.overtime.toString()
)
)
// Save to storage asynchronously
viewModelScope.launch {
try {
storage.saveRounds(newRounds)
} catch (e: Exception) {
// Storage save failed, but continue with UI update
}
}
}
}
fun deleteRound(roundId: String) {
val currentState = _state.value
deletedRound = currentState.rounds.find { it.id == roundId }
val newRounds = currentState.rounds.filter { it.id != roundId }
_state.value = currentState.copy(rounds = newRounds)
analyticsService.logEvent("round_deleted", mapOf("round_id" to roundId, "game_id" to (currentState.activeGameId ?: "")))
viewModelScope.launch {
try {
storage.saveRounds(newRounds)
} catch (e: Exception) {
// Storage save failed, but continue with UI update
}
}
}
fun undoDeleteRound() {
deletedRound?.let {
val newRounds = (_state.value.rounds + it).sortedBy { it.timestamp }
_state.value = _state.value.copy(rounds = newRounds)
analyticsService.logEvent("round_delete_undone", mapOf("game_id" to it.gameId))
viewModelScope.launch {
storage.saveRounds(newRounds)
}
}
}
fun updateRound(roundId: String, newDuration: Int, newOvertime: Int, newPhase: String, newPlayer: String) {
val currentState = _state.value
val updatedRounds = currentState.rounds.map { round ->
if (round.id == roundId) {
round.copy(
duration = newDuration,
overtime = newOvertime,
phase = newPhase,
player = newPlayer,
category = "$newPhase - $newPlayer" // Update legacy category for consistency
)
} else {
round
}
}
_state.value = currentState.copy(rounds = updatedRounds)
analyticsService.logEvent("round_updated", mapOf("round_id" to roundId, "duration" to newDuration.toString(), "phase" to newPhase, "player" to newPlayer))
viewModelScope.launch {
try {
storage.saveRounds(updatedRounds)
} catch (e: Exception) {
// Storage save failed, but continue with UI update
}
}
}
fun resetHistoryForGame(gameId: String) {
val currentState = _state.value
val roundsToDelete = currentState.rounds.filter { it.gameId == gameId }
val newRounds = currentState.rounds.filter { it.gameId != gameId }
_state.value = currentState.copy(rounds = newRounds)
analyticsService.logEvent("history_reset_for_game", mapOf("game_id" to gameId, "rounds_deleted" to roundsToDelete.size.toString()))
// Clear storage asynchronously
viewModelScope.launch {
try {
storage.saveRounds(newRounds)
} catch (e: Exception) {
// Storage clear failed, but continue with UI update
}
}
}
fun formatTime(seconds: Int): String {
val minutes = seconds / 60
val remainingSeconds = seconds % 60
return if (minutes > 0) {
"$minutes:${remainingSeconds.toString().padStart(2, '0')}"
} else {
"0:${remainingSeconds.toString().padStart(2, '0')}"
}
}
/**
* Fast forward the timer by the specified number of seconds.
* This will immediately advance the timer state and trigger any audio cues
* that should have played during the skipped time.
*/
fun fastForward(seconds: Int) {
if (!_state.value.isRunning || seconds <= 0 || !_state.value.settings.isSecretFastForwardEnabled) {
return
}
val fastForwardMs = seconds * 1000L
val currentState = _state.value
// Update the fast forward offset for UI synchronization
fastForwardOffset += fastForwardMs
// Fast forward the audio scheduler
audioScheduler.fastForward(fastForwardMs)
// The UI will automatically update on the next interval using the synchronized timing
// with the updated fastForwardOffset
analyticsService.logEvent(
"timer_fast_forwarded",
mapOf(
"game_id" to (currentState.activeGameId ?: ""),
"seconds_forwarded" to seconds.toString(),
"was_overtime" to currentState.isOvertime.toString()
)
)
}
fun createNewGame(name: String) {
val existingGame = _state.value.games.find { it.name.equals(name, ignoreCase = true) }
val newGame = Game(
id = uuid(),
date = getCurrentDate(),
name = name,
// Copy types and configurations from existing game if found, otherwise use defaults
customTypes = existingGame?.customTypes ?: emptyList(),
playerTypes = existingGame?.playerTypes ?: emptyList(),
typeConfigurations = existingGame?.typeConfigurations ?: emptyMap()
)
val updatedGames = listOf(newGame) + _state.value.games
_state.value = _state.value.copy(
games = updatedGames,
activeGameId = newGame.id,
customTypes = newGame.customTypes,
playerTypes = newGame.playerTypes,
selectedPhase = "Setup",
selectedPlayer = "Everyone"
)
viewModelScope.launch {
storage.saveGames(updatedGames)
storage.saveActiveGameId(newGame.id)
}
analyticsService.logEvent("create_new_game", mapOf("name" to name))
}
fun setActiveGame(gameId: String) {
val game = _state.value.games.find { it.id == gameId }
_state.value = _state.value.copy(
activeGameId = gameId,
customTypes = game?.customTypes ?: emptyList(),
playerTypes = game?.playerTypes ?: emptyList(),
selectedPhase = "Setup",
selectedPlayer = "Everyone",
configuredTime = game?.typeConfigurations?.get("Setup") ?: 150000L,
currentTime = game?.typeConfigurations?.get("Setup") ?: 150000L
)
analyticsService.logEvent("active_game_changed", mapOf("game_id" to gameId))
viewModelScope.launch {
storage.saveActiveGameId(gameId)
}
}
fun updateGameName(gameId: String, name: String) {
val updatedGames = _state.value.games.map {
if (it.id == gameId) {
it.copy(name = name)
} else {
it
}
}.sortedByDescending { it.id }
_state.value = _state.value.copy(games = updatedGames)
analyticsService.logEvent("game_name_updated", mapOf("game_id" to gameId, "new_name" to name))
viewModelScope.launch {
storage.saveGames(updatedGames)
}
}
fun updateSetting(settingName: String, isEnabled: Boolean) {
val currentSettings = _state.value.settings
val newSettings = when (settingName) {
"subtleDrumming" -> currentSettings.copy(isSubtleDrummingEnabled = isEnabled)
"intenseDrumming" -> currentSettings.copy(isIntenseDrummingEnabled = isEnabled)
"overtimeAlarm" -> {
if (isEnabled) {
currentSettings.copy(isOvertimeAlarmEnabled = true, isTimeoutGongEnabled = false)
} else {
currentSettings.copy(isOvertimeAlarmEnabled = false)
}
}
"timeoutGong" -> {
if (isEnabled) {
currentSettings.copy(isTimeoutGongEnabled = true, isOvertimeAlarmEnabled = false)
} else {
currentSettings.copy(isTimeoutGongEnabled = false)
}
}
"jonasScolding" -> currentSettings.copy(isJonasScoldingEnabled = isEnabled)
"secretFastForward" -> currentSettings.copy(isSecretFastForwardEnabled = isEnabled)
else -> currentSettings
}
if (newSettings != currentSettings) {
_state.value = _state.value.copy(settings = newSettings)
analyticsService.logEvent(
"setting_updated",
mapOf("setting_name" to settingName, "is_enabled" to isEnabled.toString())
)
viewModelScope.launch {
storage.saveSettings(newSettings)
}
}
}
fun deleteGame(gameId: String) {
val currentState = _state.value
deletedGame = currentState.games.find { it.id == gameId }
val newGames = currentState.games.filter { it.id != gameId }.sortedByDescending { it.id }
val newActiveGameId = if (currentState.activeGameId == gameId) {
newGames.firstOrNull()?.id
} else {
currentState.activeGameId
}
_state.value = currentState.copy(games = newGames, activeGameId = newActiveGameId)
analyticsService.logEvent("game_deleted", mapOf("game_id" to gameId))
viewModelScope.launch {
storage.saveGames(newGames)
storage.saveActiveGameId(newActiveGameId)
}
}
fun undoDeleteGame() {
deletedGame?.let {
val newGames = (_state.value.games + it).sortedByDescending { it.id }
_state.value = _state.value.copy(games = newGames)
analyticsService.logEvent("game_delete_undone", mapOf("game_id" to it.id))
viewModelScope.launch {
storage.saveGames(newGames)
}
}
}
// Category Management
fun selectPhase(phase: String) {
val activeGameId = _state.value.activeGameId
val game = _state.value.games.find { it.id == activeGameId }
// Load config for the phase
val configuredTime = game?.typeConfigurations?.get(phase) ?: 150000L
_state.value = _state.value.copy(
selectedPhase = phase,
configuredTime = configuredTime,
currentTime = configuredTime
)
analyticsService.logEvent("select_phase", mapOf("phase" to phase))
}
fun selectPlayer(player: String) {
_state.value = _state.value.copy(
selectedPlayer = player
)
analyticsService.logEvent("select_player", mapOf("player" to player))
}
// Deprecated but kept for compatibility if needed, redirects to phase selection
fun selectCategory(category: String) {
selectPhase(category)
}
fun addCustomCategory(category: String) {
val newTypes = _state.value.customTypes + category
_state.value = _state.value.copy(customTypes = newTypes)
updateActiveGameTypes(newTypes, _state.value.playerTypes)
analyticsService.logEvent("add_custom_category", mapOf("category" to category))
}
fun removeCustomCategory(category: String) {
val newTypes = _state.value.customTypes - category
_state.value = _state.value.copy(
customTypes = newTypes,
selectedPhase = if (_state.value.selectedPhase == category) "Setup" else _state.value.selectedPhase
)
updateActiveGameTypes(newTypes, _state.value.playerTypes)
analyticsService.logEvent("remove_custom_category", mapOf("category" to category))
}
fun addPlayerCategory(player: String) {
val newTypes = _state.value.playerTypes + player
_state.value = _state.value.copy(playerTypes = newTypes)
updateActiveGameTypes(_state.value.customTypes, newTypes)
analyticsService.logEvent("add_player_category", mapOf("category" to player))
}
fun removePlayerCategory(player: String) {
val newTypes = _state.value.playerTypes - player
_state.value = _state.value.copy(
playerTypes = newTypes,
selectedPlayer = if (_state.value.selectedPlayer == player) "Everyone" else _state.value.selectedPlayer
)
updateActiveGameTypes(_state.value.customTypes, newTypes)
analyticsService.logEvent("remove_player_category", mapOf("category" to player))
}
fun renameCustomCategory(oldName: String, newName: String) {
val newTypes = _state.value.customTypes.map { if (it == oldName) newName else it }
_state.value = _state.value.copy(
customTypes = newTypes,
selectedPhase = if (_state.value.selectedPhase == oldName) newName else _state.value.selectedPhase
)
updateActiveGameTypes(newTypes, _state.value.playerTypes)
analyticsService.logEvent("rename_custom_category", mapOf("oldName" to oldName, "newName" to newName))
}
fun renamePlayerCategory(oldName: String, newName: String) {
val newTypes = _state.value.playerTypes.map { if (it == oldName) newName else it }
_state.value = _state.value.copy(
playerTypes = newTypes,
selectedPlayer = if (_state.value.selectedPlayer == oldName) newName else _state.value.selectedPlayer
)
updateActiveGameTypes(_state.value.customTypes, newTypes)
analyticsService.logEvent("rename_player_category", mapOf("oldName" to oldName, "newName" to newName))
}
fun getPreviouslyUsedPlayerNames(): List<String> {
return _state.value.games
.flatMap { it.playerTypes }
.distinct()
.sorted()
}
private fun updateActiveGameTypes(customTypes: List<String>, playerTypes: List<String>) {
val activeGameId = _state.value.activeGameId ?: return
val updatedGames = _state.value.games.map { game ->
if (game.id == activeGameId) {
game.copy(customTypes = customTypes, playerTypes = playerTypes)
} else {
game
}
}
_state.value = _state.value.copy(games = updatedGames)
viewModelScope.launch {
storage.saveGames(updatedGames)
}
}
override fun onCleared() {
super.onCleared()
timerJob?.cancel()
audioScheduler.stop()
soundPlayer.cleanup()
}
private fun uuid(): String {
val charPool = "0123456789abcdef"
return (1..32)
.map { charPool[Random.nextInt(0, charPool.length)] }
.joinToString("")
.let {
"${it.substring(0, 8)}-${it.substring(8, 12)}-${it.substring(12, 16)}-${it.substring(16, 20)}-${it.substring(20, 32)}"
}
}
}