-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathAlarmAddEditViewModel.kt
534 lines (475 loc) Β· 21.4 KB
/
AlarmAddEditViewModel.kt
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
package com.yapp.alarm.addedit
import android.util.Log
import androidx.compose.ui.unit.dp
import androidx.lifecycle.SavedStateHandle
import androidx.lifecycle.viewModelScope
import com.yapp.alarm.AlarmHelper
import com.yapp.common.util.ResourceProvider
import com.yapp.domain.model.Alarm
import com.yapp.domain.model.AlarmDay
import com.yapp.domain.model.AlarmSound
import com.yapp.domain.model.copyFrom
import com.yapp.domain.model.toAlarmDays
import com.yapp.domain.model.toDayOfWeek
import com.yapp.domain.usecase.AlarmUseCase
import com.yapp.media.haptic.HapticFeedbackManager
import com.yapp.media.haptic.HapticType
import com.yapp.ui.base.BaseViewModel
import dagger.hilt.android.lifecycle.HiltViewModel
import feature.home.R
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.launch
import java.time.LocalTime
import javax.inject.Inject
@HiltViewModel
class AlarmAddEditViewModel @Inject constructor(
private val alarmUseCase: AlarmUseCase,
private val resourceProvider: ResourceProvider,
private val hapticFeedbackManager: HapticFeedbackManager,
private val alarmHelper: AlarmHelper,
savedStateHandle: SavedStateHandle,
) : BaseViewModel<AlarmAddEditContract.State, AlarmAddEditContract.SideEffect>(
initialState = AlarmAddEditContract.State(),
) {
private val alarmId: Long = savedStateHandle.get<Long>("alarmId") ?: -1
init {
updateState { copy(mode = if (alarmId == -1L) AlarmAddEditContract.EditMode.ADD else AlarmAddEditContract.EditMode.EDIT) }
initializeAlarmScreen()
}
private fun initializeAlarmScreen() = viewModelScope.launch {
alarmUseCase.getAlarmSounds().onSuccess { sounds ->
if (alarmId == -1L) {
setupNewAlarmScreen(sounds)
} else {
loadExistingAlarm(sounds)
}
}.onFailure {
Log.e("AlarmAddEditViewModel", "Failed to load alarm sounds", it)
}
}
private fun setupNewAlarmScreen(sounds: List<AlarmSound>) {
val defaultSoundIndex = sounds.indexOfFirst { it.title == "Homecoming" }.takeIf { it >= 0 } ?: 0
val defaultSound = sounds[defaultSoundIndex]
alarmUseCase.initializeSoundPlayer(defaultSound.uri)
val now = LocalTime.now()
val initialAmPm = if (now.hour < 12) "μ€μ " else "μ€ν"
val initialHour = if (now.hour == 0 || now.hour == 12) 12 else now.hour % 12
val initialMinute = now.minute
updateState {
copy(
initialLoading = false,
timeState = timeState.copy(
initialAmPm = initialAmPm,
initialHour = "$initialHour",
initialMinute = initialMinute.toString().padStart(2, '0'),
currentAmPm = initialAmPm,
currentHour = initialHour,
currentMinute = initialMinute,
alarmMessage = getAlarmMessage(initialAmPm, initialHour, initialMinute, emptySet()),
),
soundState = soundState.copy(sounds = sounds, soundIndex = defaultSoundIndex),
)
}
}
private suspend fun loadExistingAlarm(sounds: List<AlarmSound>) {
alarmUseCase.getAlarm(alarmId).onSuccess { alarm ->
val repeatDays = alarm.repeatDays.toAlarmDays()
val isAM = alarm.isAm
val hour = alarm.hour
val selectedSoundIndex = sounds.indexOfFirst { it.uri.toString() == alarm.soundUri }
val selectedSound = sounds.getOrNull(selectedSoundIndex) ?: sounds.first()
alarmUseCase.initializeSoundPlayer(selectedSound.uri)
updateState {
copy(
initialLoading = false,
timeState = timeState.copy(
initialAmPm = if (isAM) "μ€μ " else "μ€ν",
initialHour = "$hour",
initialMinute = alarm.minute.toString().padStart(2, '0'),
currentAmPm = if (isAM) "μ€μ " else "μ€ν",
currentHour = hour,
currentMinute = alarm.minute,
alarmMessage = getAlarmMessage(if (isAM) "μ€μ " else "μ€ν", hour, alarm.minute, repeatDays),
),
daySelectionState = setupDaySelectionState(repeatDays),
holidayState = holidayState.copy(
isDisableHolidayEnabled = repeatDays.isNotEmpty(),
isDisableHolidayChecked = alarm.isHolidayAlarmOff,
),
snoozeState = setupSnoozeState(alarm),
soundState = soundState.copy(
isVibrationEnabled = alarm.isVibrationEnabled,
isSoundEnabled = alarm.isSoundEnabled,
soundVolume = alarm.soundVolume,
sounds = sounds,
soundIndex = selectedSoundIndex,
),
)
}
}
}
private fun setupDaySelectionState(repeatDays: Set<AlarmDay>) = currentState.daySelectionState.copy(
selectedDays = repeatDays,
isWeekdaysChecked = repeatDays.containsAll(setOf(AlarmDay.MON, AlarmDay.TUE, AlarmDay.WED, AlarmDay.THU, AlarmDay.FRI)),
isWeekendsChecked = repeatDays.containsAll(setOf(AlarmDay.SAT, AlarmDay.SUN)),
)
private fun setupSnoozeState(alarm: Alarm) = currentState.snoozeState.copy(
isSnoozeEnabled = alarm.isSnoozeEnabled,
snoozeIntervalIndex = findSnoozeIndex(alarm.snoozeInterval, currentState.snoozeState.snoozeIntervals),
snoozeCountIndex = findSnoozeIndex(alarm.snoozeCount, currentState.snoozeState.snoozeCounts),
)
private fun findSnoozeIndex(value: Int, list: List<String>): Int {
return list.indexOfFirst {
it == "무ν" && value == -1 || it.filter { char -> char.isDigit() }.toIntOrNull() == value
}.takeIf { it >= 0 } ?: 0
}
override fun onCleared() {
super.onCleared()
alarmUseCase.releaseSoundPlayer()
}
fun processAction(action: AlarmAddEditContract.Action) {
when (action) {
is AlarmAddEditContract.Action.CheckUnsavedChangesBeforeExit -> checkUnsavedChangesBeforeExit()
is AlarmAddEditContract.Action.NavigateBack -> navigateBack()
is AlarmAddEditContract.Action.SaveAlarm -> saveAlarm()
is AlarmAddEditContract.Action.ShowDeleteDialog -> showDeleteDialog()
is AlarmAddEditContract.Action.HideDeleteDialog -> hideDeleteDialog()
is AlarmAddEditContract.Action.ShowUnsavedChangesDialog -> showUnsavedChangesDialog()
is AlarmAddEditContract.Action.HideUnsavedChangesDialog -> hideUnsavedChangesDialog()
is AlarmAddEditContract.Action.DeleteAlarm -> deleteAlarm()
is AlarmAddEditContract.Action.SetAlarmTime -> setAlarmTime(action.amPm, action.hour, action.minute)
is AlarmAddEditContract.Action.ToggleWeekdaysSelection -> toggleWeekdaysSelection()
is AlarmAddEditContract.Action.ToggleWeekendsSelection -> toggleWeekendsSelection()
is AlarmAddEditContract.Action.ToggleSpecificDaySelection -> toggleSpecificDaySelection(action.day)
is AlarmAddEditContract.Action.ToggleHolidaySkipOption -> toggleHolidaySkipOption()
is AlarmAddEditContract.Action.ToggleSnoozeOption -> toggleSnoozeOption()
is AlarmAddEditContract.Action.SetSnoozeInterval -> setSnoozeInterval(action.index)
is AlarmAddEditContract.Action.SetSnoozeRepeatCount -> setSnoozeRepeatCount(action.index)
is AlarmAddEditContract.Action.ToggleVibrationOption -> toggleVibrationOption()
is AlarmAddEditContract.Action.ToggleSoundOption -> toggleSoundOption()
is AlarmAddEditContract.Action.AdjustSoundVolume -> adjustSoundVolume(action.volume)
is AlarmAddEditContract.Action.SelectAlarmSound -> selectAlarmSound(action.index)
is AlarmAddEditContract.Action.ToggleBottomSheet -> toggleBottomSheet(action.sheetType)
}
}
private fun checkUnsavedChangesBeforeExit() {
if (currentState.mode == AlarmAddEditContract.EditMode.ADD) {
navigateBack()
} else {
val updatedAlarm = currentState.toAlarm()
viewModelScope.launch {
alarmUseCase.getAlarm(alarmId).onSuccess { existingAlarm ->
if (updatedAlarm.copy(id = alarmId) != existingAlarm) {
showUnsavedChangesDialog()
} else {
emitSideEffect(AlarmAddEditContract.SideEffect.NavigateBack)
}
}
}
}
}
private fun navigateBack() {
emitSideEffect(AlarmAddEditContract.SideEffect.NavigateBack)
}
private fun saveAlarm() {
val newAlarm = currentState.toAlarm()
viewModelScope.launch {
when (currentState.mode) {
AlarmAddEditContract.EditMode.EDIT -> updateExistingAlarm(newAlarm)
AlarmAddEditContract.EditMode.ADD -> checkAndCreateAlarm(newAlarm)
}
}
}
private suspend fun updateExistingAlarm(alarm: Alarm) {
val updatedAlarm = alarm.copy(id = alarmId)
alarmUseCase.getAlarm(alarmId).onSuccess { oldAlarm ->
alarmHelper.unScheduleAlarm(oldAlarm)
}
alarmUseCase.updateAlarm(updatedAlarm)
.onSuccess {
alarmHelper.scheduleAlarm(updatedAlarm)
emitSideEffect(AlarmAddEditContract.SideEffect.UpdateAlarm(it.id))
}
.onFailure {
Log.e("AlarmAddEditViewModel", "Failed to update alarm", it)
}
}
private suspend fun checkAndCreateAlarm(newAlarm: Alarm) {
val timeMatchedAlarms = alarmUseCase.getAlarmsByTime(newAlarm.hour, newAlarm.minute, newAlarm.isAm)
.first()
when {
timeMatchedAlarms.any { it.copy(id = 0) == newAlarm.copy(id = 0) } -> {
showAlarmAlreadySetWarning()
}
timeMatchedAlarms.isNotEmpty() -> {
val existingAlarm = timeMatchedAlarms.first()
val updatedAlarm = existingAlarm.copyFrom(newAlarm).copy(id = existingAlarm.id)
updateExistingAlarm(updatedAlarm)
}
else -> {
createNewAlarm(newAlarm)
}
}
}
private fun showAlarmAlreadySetWarning() {
emitSideEffect(
AlarmAddEditContract.SideEffect.ShowSnackBar(
message = resourceProvider.getString(R.string.alarm_already_set),
iconRes = resourceProvider.getDrawable(core.designsystem.R.drawable.ic_alert),
bottomPadding = 78.dp,
onDismiss = { },
onAction = { },
),
)
}
private suspend fun createNewAlarm(alarm: Alarm) {
alarmUseCase.insertAlarm(alarm)
.onSuccess {
alarmHelper.scheduleAlarm(it)
emitSideEffect(AlarmAddEditContract.SideEffect.SaveAlarm(it.id))
}
.onFailure {
Log.e("AlarmAddEditViewModel", "Failed to insert alarm", it)
}
}
private fun setAlarmTime(amPm: String, hour: Int, minute: Int) {
val newTimeState = currentState.timeState.copy(
currentAmPm = amPm,
currentHour = hour,
currentMinute = minute,
alarmMessage = getAlarmMessage(amPm, hour, minute, currentState.daySelectionState.selectedDays),
)
hapticFeedbackManager.performHapticFeedback(HapticType.LIGHT_TICK)
updateState {
copy(timeState = newTimeState)
}
}
private fun showDeleteDialog() {
updateState { copy(isDeleteDialogVisible = true) }
}
private fun hideDeleteDialog() {
updateState { copy(isDeleteDialogVisible = false) }
}
private fun showUnsavedChangesDialog() {
updateState { copy(isUnsavedChangesDialogVisible = true) }
}
private fun hideUnsavedChangesDialog() {
updateState { copy(isUnsavedChangesDialogVisible = false) }
}
private fun deleteAlarm() {
emitSideEffect(AlarmAddEditContract.SideEffect.DeleteAlarm(alarmId))
}
private fun toggleWeekdaysSelection() {
val weekdays = setOf(AlarmDay.MON, AlarmDay.TUE, AlarmDay.WED, AlarmDay.THU, AlarmDay.FRI)
val isChecked = !currentState.daySelectionState.isWeekdaysChecked
val updatedDays = if (isChecked) {
currentState.daySelectionState.selectedDays + weekdays
} else {
currentState.daySelectionState.selectedDays - weekdays
}
val newDayState = currentState.daySelectionState.copy(
isWeekdaysChecked = isChecked,
selectedDays = updatedDays,
)
updateState {
copy(
timeState = timeState.copy(
alarmMessage = getAlarmMessage(timeState.currentAmPm, timeState.currentHour, timeState.currentMinute, newDayState.selectedDays),
),
daySelectionState = newDayState,
holidayState = holidayState.copy(
isDisableHolidayEnabled = newDayState.selectedDays.isNotEmpty(),
isDisableHolidayChecked = if (newDayState.selectedDays.isEmpty()) false else holidayState.isDisableHolidayChecked,
),
)
}
}
private fun toggleWeekendsSelection() {
val weekends = setOf(AlarmDay.SAT, AlarmDay.SUN)
val isChecked = !currentState.daySelectionState.isWeekendsChecked
val updatedDays = if (isChecked) {
currentState.daySelectionState.selectedDays + weekends
} else {
currentState.daySelectionState.selectedDays - weekends
}
val newDayState = currentState.daySelectionState.copy(
isWeekendsChecked = isChecked,
selectedDays = updatedDays,
)
updateState {
copy(
timeState = timeState.copy(
alarmMessage = getAlarmMessage(timeState.currentAmPm, timeState.currentHour, timeState.currentMinute, newDayState.selectedDays),
),
daySelectionState = newDayState,
holidayState = holidayState.copy(
isDisableHolidayEnabled = newDayState.selectedDays.isNotEmpty(),
isDisableHolidayChecked = if (newDayState.selectedDays.isEmpty()) false else holidayState.isDisableHolidayChecked,
),
)
}
}
private fun toggleSpecificDaySelection(day: AlarmDay) {
val updatedDays = if (day in currentState.daySelectionState.selectedDays) {
currentState.daySelectionState.selectedDays - day
} else {
currentState.daySelectionState.selectedDays + day
}
val weekdays = setOf(AlarmDay.MON, AlarmDay.TUE, AlarmDay.WED, AlarmDay.THU, AlarmDay.FRI)
val weekends = setOf(AlarmDay.SAT, AlarmDay.SUN)
val newDayState = currentState.daySelectionState.copy(
selectedDays = updatedDays,
isWeekdaysChecked = updatedDays.containsAll(weekdays),
isWeekendsChecked = updatedDays.containsAll(weekends),
)
updateState {
copy(
timeState = timeState.copy(
alarmMessage = getAlarmMessage(timeState.currentAmPm, timeState.currentHour, timeState.currentMinute, newDayState.selectedDays),
),
daySelectionState = newDayState,
holidayState = holidayState.copy(
isDisableHolidayEnabled = newDayState.selectedDays.isNotEmpty(),
isDisableHolidayChecked = if (newDayState.selectedDays.isEmpty()) false else holidayState.isDisableHolidayChecked,
),
)
}
}
private fun toggleHolidaySkipOption() {
val newHolidayState = currentState.holidayState.copy(
isDisableHolidayChecked = !currentState.holidayState.isDisableHolidayChecked,
)
updateState {
copy(holidayState = newHolidayState)
}
if (newHolidayState.isDisableHolidayChecked) {
emitSideEffect(
AlarmAddEditContract.SideEffect.ShowSnackBar(
message = resourceProvider.getString(R.string.alarm_disabled_warning),
label = resourceProvider.getString(R.string.alarm_delete_dialog_btn_cancel),
iconRes = resourceProvider.getDrawable(core.designsystem.R.drawable.ic_check_green),
bottomPadding = 78.dp,
onDismiss = { },
onAction = {
updateState {
copy(holidayState = holidayState.copy(isDisableHolidayChecked = false))
}
},
),
)
}
}
private fun toggleSnoozeOption() {
val newSnoozeState = currentState.snoozeState.copy(
isSnoozeEnabled = !currentState.snoozeState.isSnoozeEnabled,
)
updateState {
copy(snoozeState = newSnoozeState)
}
}
private fun setSnoozeInterval(index: Int) {
val newSnoozeState = currentState.snoozeState.copy(snoozeIntervalIndex = index)
updateState {
copy(snoozeState = newSnoozeState)
}
}
private fun setSnoozeRepeatCount(index: Int) {
val newSnoozeState = currentState.snoozeState.copy(snoozeCountIndex = index)
updateState {
copy(snoozeState = newSnoozeState)
}
}
private fun toggleVibrationOption() {
val newSoundState = currentState.soundState.copy(isVibrationEnabled = !currentState.soundState.isVibrationEnabled)
if (newSoundState.isVibrationEnabled) {
hapticFeedbackManager.performHapticFeedback(HapticType.SUCCESS)
}
updateState {
copy(soundState = newSoundState)
}
}
private fun toggleSoundOption() {
val newSoundState = currentState.soundState.copy(isSoundEnabled = !currentState.soundState.isSoundEnabled)
if (!newSoundState.isSoundEnabled) {
alarmUseCase.stopAlarmSound()
}
updateState {
copy(soundState = newSoundState)
}
}
private fun adjustSoundVolume(volume: Int) {
val newSoundState = currentState.soundState.copy(soundVolume = volume)
alarmUseCase.updateAlarmVolume(volume)
updateState {
copy(soundState = newSoundState)
}
}
private fun selectAlarmSound(index: Int) {
val newSoundState = currentState.soundState.copy(soundIndex = index)
updateState {
copy(soundState = newSoundState)
}
val selectedSound = currentState.soundState.sounds[index]
alarmUseCase.initializeSoundPlayer(selectedSound.uri)
alarmUseCase.playAlarmSound(currentState.soundState.soundVolume)
}
private fun toggleBottomSheet(sheetType: AlarmAddEditContract.BottomSheetType) {
val newBottomSheetState = if (currentState.bottomSheetState == sheetType) {
if (currentState.bottomSheetState == AlarmAddEditContract.BottomSheetType.SoundSetting) {
alarmUseCase.stopAlarmSound()
}
null
} else {
sheetType
}
updateState {
copy(bottomSheetState = newBottomSheetState)
}
}
private fun getAlarmMessage(amPm: String, hour: Int, minute: Int, selectedDays: Set<AlarmDay>): String {
val now = java.time.LocalDateTime.now()
val alarmHour = convertTo24HourFormat(amPm, hour)
val alarmTimeToday = now.toLocalDate().atTime(alarmHour, minute)
val nextAlarmDateTime = calculateNextAlarmDateTime(now, alarmTimeToday, selectedDays)
val duration = java.time.Duration.between(now, nextAlarmDateTime)
val totalMinutes = duration.toMinutes()
val days = totalMinutes / (24 * 60)
val hours = (totalMinutes % (24 * 60)) / 60
val minutes = totalMinutes % 60
return when {
days > 0 -> "${days}μΌ ${hours}μκ° νμ μΈλ €μ"
hours > 0 -> "${hours}μκ° ${minutes}λΆ νμ μΈλ €μ"
minutes == 0L -> "곧 μΈλ €μ"
else -> "${minutes}λΆ νμ μΈλ €μ"
}
}
private fun convertTo24HourFormat(amPm: String, hour: Int): Int = when {
amPm == "μ€ν" && hour != 12 -> hour + 12
amPm == "μ€μ " && hour == 12 -> 0
else -> hour
}
private fun calculateNextAlarmDateTime(
now: java.time.LocalDateTime,
alarmTimeToday: java.time.LocalDateTime,
selectedDays: Set<AlarmDay>,
): java.time.LocalDateTime {
if (selectedDays.isEmpty()) {
return if (alarmTimeToday.isBefore(now)) {
alarmTimeToday.plusDays(1)
} else {
alarmTimeToday
}
}
val currentDayOfWeek = now.dayOfWeek.value
val selectedDaysOfWeek = selectedDays.map { it.toDayOfWeek().value }.sorted()
val nextDay = selectedDaysOfWeek.firstOrNull { it > currentDayOfWeek }
?: selectedDaysOfWeek.first()
val daysToAdd = if (nextDay > currentDayOfWeek) {
nextDay - currentDayOfWeek
} else {
7 - (currentDayOfWeek - nextDay)
}
val nextAlarmDate = now.toLocalDate().plusDays(daysToAdd.toLong())
return nextAlarmDate.atTime(alarmTimeToday.toLocalTime())
}
}