-
-
Notifications
You must be signed in to change notification settings - Fork 19
/
Copy pathMagicTimer.swift
195 lines (167 loc) · 6.73 KB
/
MagicTimer.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
import Foundation
import MathOperators
@available(*, unavailable, renamed: "MagicTimerMode")
/// The timer counting mode.
public enum MGCountMode {
case stopWatch
case countDown(fromSeconds: TimeInterval)
}
public enum MagicTimerMode {
case stopWatch
case countDown(fromSeconds: TimeInterval)
}
/// The MagicTimer class is a timer implementation. It provides various functionalities to start, stop, reset, background time calculation and more.
public class MagicTimer {
// MARK: - Typealias
public typealias StateHandler = ((MagicTimerState) -> Void)
public typealias ElapsedTimeHandler = ((TimeInterval) -> Void)
// MARK: - Public properties
// MARK: - Handlers
/// Last state of the timer handler. It calls when state of timer changes.
public var lastStateDidChangeHandler: StateHandler?
/// Elapsed time handler. It calls on each timeInterval.
public var elapsedTimeDidChangeHandler: ElapsedTimeHandler?
// MARK: - Get only properties
/// Last state of the timer. Checkout ```MagicTimerState```.
public private(set) var lastState: MagicTimerState = .none {
didSet {
lastStateDidChangeHandler?(lastState)
}
}
/// Elapsed time from where the timer started. Default is 0.
public private(set) var elapsedTime: TimeInterval = 0 {
didSet {
elapsedTimeDidChangeHandler?(elapsedTime)
}
}
/// Timer count mode. Default is `.stopWatch`. Checkout ```MagicTimerMode```.
public var countMode: MagicTimerMode = .stopWatch
/// Timer default value. Default is 0.
public var defultValue: TimeInterval = 0 {
didSet {
guard defultValue.isBiggerThanOrEqual(.zero) else {
fatalError("The defultValue should be greater or equal to zero.")
}
counter.defultValue = defultValue
}
}
/// A number which is added or minused on each ``timeInterval``. Default is 1.
public var effectiveValue: TimeInterval = 1 {
didSet {
guard effectiveValue.isBiggerThanOrEqual(.zero) else {
fatalError("The effectiveValue should be greater or equal to zero.")
}
counter.effectiveValue = effectiveValue
}
}
/// Timer time interval. Default is 1.
public var timeInterval: TimeInterval = 1 {
didSet {
guard timeInterval.isBiggerThanOrEqual(.zero) else {
fatalError("The timeInterval should be greater or equal to zero.")
}
executive.timeInterval = timeInterval
}
}
/// By changing this type timer decides to whether calcualte the time in background. Default is true.
public var isActiveInBackground: Bool = true {
didSet {
backgroundCalculator.isActiveBackgroundMode = isActiveInBackground
}
}
// MARK: - Private properties
private var counter: MagicTimerCounterInterface
private var executive: MagicTimerExecutiveInterface
private var backgroundCalculator: MagicTimerBackgroundCalculatorInterface
// MARK: - Unavailable
/// A elapsed time that can observe
/// - Warning: renamed: "elapsedTimeDidChangeHandler"
public var observeElapsedTime: ((TimeInterval) -> Void)?
/// The current state of the timer.
/// - Warning: renamed: "lastState"
public var currentState: MagicTimerState {
return lastState
}
/// Timer state callback
/// - Warning: renamed: "lastStateDidChangeHandler"
public var didStateChange: ((MagicTimerState) -> Void)?
// MARK: - Constructors
public init(counter: MagicTimerCounterInterface = MagicTimerCounter(),
executive: MagicTimerExecutiveInterface = MagicTimerExecutive(),
backgroundCalculator: MagicTimerBackgroundCalculatorInterface = MagicTimerBackgroundCalculator()) {
self.counter = counter
self.executive = executive
self.backgroundCalculator = backgroundCalculator
self.backgroundCalculator.backgroundTimeCalculateHandler = { elapsedTime in
self.calculateBackgroundTime(elapsedTime: elapsedTime)
}
}
// MARK: - Public methods
/// Start counting the timer.
public func start() {
executive.fire {
self.backgroundCalculator.timerFiredDate = Date()
self.lastState = .fired
self.observeScheduleTimer()
}
}
/// Stop counting the timer.
public func stop() {
executive.suspand {
self.lastState = .stopped
}
}
/// Reset the timer. It will set the elapsed time to zero.
public func reset() {
executive.suspand {
self.counter.resetTotalCounted()
self.lastState = .restarted
}
}
/// Reset the timer to the ``defaultvalue``.
public func resetToDefault() {
executive.suspand {
self.counter.resetToDefaultValue()
self.lastState = .restarted
}
}
// MARK: - Private methods
// It calculates the elapsed time user was in background.
private func calculateBackgroundTime(elapsedTime: TimeInterval) {
switch countMode {
case .stopWatch:
counter.totalCountedValue = elapsedTime
case let .countDown(fromSeconds: countDownSeconds):
let totalCountedValue = countDownSeconds + elapsedTime
let subtraction = countDownSeconds - elapsedTime
if subtraction.isPositive {
counter.totalCountedValue = totalCountedValue
} else {
counter.totalCountedValue = 1
}
}
}
private func observeScheduleTimer() {
executive.scheduleTimerHandler = { [weak self] in
guard let self else { return }
switch self.countMode {
case .stopWatch:
self.counter.add()
self.elapsedTime = self.counter.totalCountedValue
case .countDown(let fromSeconds):
// Checking if defaultValue plus fromSeconds not going to invalid format(negative seconds).
guard (self.defultValue + fromSeconds).truncatingRemainder(dividingBy: self.effectiveValue).isEqual(to: .zero) else {
fatalError("The time does not lead to a valid format. Use valid effetiveValue")
}
guard counter.totalCountedValue.isBiggerThan(.zero) else {
executive.suspand {
self.lastState = .stopped
}
return
}
counter.subtract()
elapsedTime = self.counter.totalCountedValue
}
}
}
}