-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathTimerViewModel.swift
213 lines (184 loc) · 6.81 KB
/
TimerViewModel.swift
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
//
// TimerViewModel.swift
// Focal
//
// Created by Niek van de Pas on 12/03/2024.
//
import SwiftUI
import Combine
@MainActor
class TimerViewModel: ObservableObject {
static let shared = TimerViewModel()
@Published var timeRemaining: Int
@Published private var _timerIsRunning = false
@Published var confettiCounter: Int = 0
@Published var workTimerName: String = "Work"
@Published var restTimerName: String = "Rest"
var timerIsRunning: Bool {
get { return _timerIsRunning }
set {
if newValue == true {
self.initializeTimer()
}
else {
self.timer = nil
NotificationManager.removeAllNotificationRequests()
self.notificationScheduled = false
}
_timerIsRunning = newValue
}
}
@Published var timerState: TimerState = .work
@Published var completedSessions = 0
var notificationScheduled = false
private let settingsManager = SettingsManager.shared
private var timer: AnyCancellable?
init() {
self.timeRemaining = settingsManager.workTimerDuration
self.updateUserDefaults()
}
func startTimer() {
timerIsRunning = true
self.updateUserDefaults()
}
func pauseTimer() {
timerIsRunning = false
self.updateUserDefaults()
}
func resetTimer() {
timerState = .work
timeRemaining = settingsManager.workTimerDuration
timerIsRunning = false
completedSessions = 0
self.updateUserDefaults()
}
func skipBreakTimer() {
timerState = .work
self.resetTimerDuration()
NotificationManager.removeAllNotificationRequests()
completedSessions += 1
timerIsRunning = settingsManager.continuousMode
}
func updateUserDefaults() {
if let userDefaults = UserDefaults(suiteName: Constants.UD_GROUP_NAME) {
userDefaults.set(timeRemaining, forKey: Constants.UD_TIME_REMAINING)
userDefaults.set(timerIsRunning, forKey: Constants.UD_TIMER_IS_RUNNING)
userDefaults.set(timerState.rawValue, forKey: Constants.UD_TIMER_STATE)
userDefaults.set(getNextTimerState().rawValue, forKey: Constants.UD_NEXT_TIMER_STATE)
userDefaults.set(settingsManager.showTimeLeft, forKey: Constants.UD_SHOW_TIME_LEFT_SETTING)
}
}
func resetTimerDuration() {
timeRemaining = timerState == .work ? settingsManager.workTimerDuration : settingsManager.restTimerDuration
timerIsRunning = false
}
/// Returns true if the timer is at its full work duration, indicating it is reset or not started.
var timerIsFull: Bool {
return timeRemaining == settingsManager.workTimerDuration
}
var timeRemainingFormatted: String {
"\(timeRemaining / 60):\(String(format: "%02d", timeRemaining % 60))"
}
/// Returns whatever the timer state will be after the current timer is finished.
func getNextTimerState() -> TimerState {
switch self.timerState {
case .work:
// completedSessions only rolls over after the break, so we need to check for sessionGoal - 1
return self.completedSessions >= settingsManager.sessionGoal - 1 ? .longRest : .rest
case .rest:
return .work
case .longRest:
return .work
}
}
/// Returns whatever the number of completed sessions will be after the current timer is finished.
func getNextCompletedSessions() -> Int {
switch self.timerState {
case .work:
return self.completedSessions
case .rest:
return self.completedSessions + 1
case .longRest:
return 0
}
}
private func initializeTimer() {
self.timer = Timer.publish(every: 1, on: .main, in: .common)
.autoconnect()
.sink(receiveValue: self.handleTimerTick)
}
private func handleTimerTick(_: Date) {
Task {
if self.timerIsRunning && !self.notificationScheduled {
await self.scheduleTimerFinishedNotification()
}
}
if self.timeRemaining > 0 {
self.timeRemaining -= 1
} else {
self.handleTimerFinished()
}
}
private func handleTimerFinished() {
#if os(macOS)
if SettingsManager.shared.continuousMode {
// If the timer is in this 'continuous mode',
// we need to schedule the next notification immediately when the timer elapses.
// Normally, this is done when the timer is manually unpaused,
// but that never happens in this mode.
Task {
await self.scheduleTimerFinishedNotification()
}
}
else {
self.pauseTimer()
}
if SettingsManager.shared.showAppOnTimerElapse {
NSApplication.shared.activate(ignoringOtherApps: true)
if let mainWindow = NSApplication.shared.windows.first(where: { $0.title == "Focal" }) {
mainWindow.makeKeyAndOrderFront(nil)
}
}
#endif
let nextTimerState = getNextTimerState()
switch self.timerState {
case .rest:
self.completedSessions += 1
self.timeRemaining = settingsManager.workTimerDuration
case .work:
// The completedSessions counter only rolls over after the break,
// so we need to check for sessionGoal - 1 here.
if completedSessions == settingsManager.sessionGoal - 1 {
showConfetti()
}
self.timeRemaining = getTimerDuration(forTimerState: nextTimerState)
case .longRest:
self.resetTimer()
}
self.timerState = nextTimerState
self.updateUserDefaults()
}
private func getTimerDuration(forTimerState timerState: TimerState) -> Int {
switch timerState {
case .work:
return settingsManager.workTimerDuration
case .rest:
return settingsManager.restTimerDuration
case .longRest:
return settingsManager.longRestTimerDuration
}
}
private func scheduleTimerFinishedNotification() async {
let nextTimerState = getNextTimerState()
let notificationScheduled = await NotificationManager.scheduleNotification(
for: Date().addingTimeInterval(TimeInterval(self.timeRemaining)),
withSound: NotificationSound(rawValue: settingsManager.notificationSound) ?? .bell,
currentTimerState: self.timerState,
nextTimerState: nextTimerState)
self.notificationScheduled = notificationScheduled
}
private func showConfetti() {
// Incrementing the counter causes confetti to be shown
self.confettiCounter += 1
}
}