DailyValueSchedule.swift 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275
  1. //
  2. // QuantitySchedule.swift
  3. // Naterade
  4. //
  5. // Created by Nathan Racklyeft on 1/18/16.
  6. // Copyright © 2016 Nathan Racklyeft. All rights reserved.
  7. //
  8. import Foundation
  9. import HealthKit
  10. public struct RepeatingScheduleValue<T> {
  11. public var startTime: TimeInterval
  12. public var value: T
  13. public init(startTime: TimeInterval, value: T) {
  14. self.startTime = startTime
  15. self.value = value
  16. }
  17. public func map<U>(_ transform: (T) -> U) -> RepeatingScheduleValue<U> {
  18. return RepeatingScheduleValue<U>(startTime: startTime, value: transform(value))
  19. }
  20. }
  21. extension RepeatingScheduleValue: Equatable where T: Equatable {
  22. public static func == (lhs: RepeatingScheduleValue, rhs: RepeatingScheduleValue) -> Bool {
  23. return abs(lhs.startTime - rhs.startTime) < .ulpOfOne && lhs.value == rhs.value
  24. }
  25. }
  26. extension RepeatingScheduleValue: Hashable where T: Hashable {}
  27. public struct AbsoluteScheduleValue<T>: TimelineValue {
  28. public let startDate: Date
  29. public let endDate: Date
  30. public let value: T
  31. }
  32. extension AbsoluteScheduleValue: Equatable where T: Equatable {}
  33. extension RepeatingScheduleValue: RawRepresentable where T: RawRepresentable {
  34. public typealias RawValue = [String: Any]
  35. public init?(rawValue: RawValue) {
  36. guard let startTime = rawValue["startTime"] as? Double,
  37. let rawValue = rawValue["value"] as? T.RawValue,
  38. let value = T(rawValue: rawValue) else
  39. {
  40. return nil
  41. }
  42. self.init(startTime: startTime, value: value)
  43. }
  44. public var rawValue: RawValue {
  45. return [
  46. "startTime": startTime,
  47. "value": value.rawValue
  48. ]
  49. }
  50. }
  51. extension RepeatingScheduleValue: Codable where T: Codable {}
  52. public protocol DailySchedule {
  53. associatedtype T
  54. var items: [RepeatingScheduleValue<T>] { get }
  55. var timeZone: TimeZone { get set }
  56. func between(start startDate: Date, end endDate: Date) -> [AbsoluteScheduleValue<T>]
  57. func value(at time: Date) -> T
  58. }
  59. public extension DailySchedule {
  60. func value(at time: Date) -> T {
  61. return between(start: time, end: time).first!.value
  62. }
  63. }
  64. extension DailySchedule where T: Comparable {
  65. public func valueRange() -> ClosedRange<T> {
  66. items.range(of: { $0.value })!
  67. }
  68. }
  69. public struct DailyValueSchedule<T>: DailySchedule {
  70. let referenceTimeInterval: TimeInterval
  71. var repeatInterval = TimeInterval(hours: 24)
  72. public let items: [RepeatingScheduleValue<T>]
  73. public var timeZone: TimeZone
  74. public init?(dailyItems: [RepeatingScheduleValue<T>], timeZone: TimeZone? = nil) {
  75. self.items = dailyItems.sorted { $0.startTime < $1.startTime }
  76. self.timeZone = timeZone ?? TimeZone.currentFixed
  77. guard let firstItem = self.items.first else {
  78. return nil
  79. }
  80. referenceTimeInterval = firstItem.startTime
  81. }
  82. var maxTimeInterval: TimeInterval {
  83. return referenceTimeInterval + repeatInterval
  84. }
  85. /**
  86. Returns the time interval for a given date normalized to the span of the schedule items
  87. - parameter date: The date to convert
  88. */
  89. func scheduleOffset(for date: Date) -> TimeInterval {
  90. // The time interval since a reference date in the specified time zone
  91. let interval = date.timeIntervalSinceReferenceDate + TimeInterval(timeZone.secondsFromGMT(for: date))
  92. // The offset of the time interval since the last occurence of the reference time + n * repeatIntervals.
  93. // If the repeat interval was 1 day, this is the fractional amount of time since the most recent repeat interval starting at the reference time
  94. return ((interval - referenceTimeInterval).truncatingRemainder(dividingBy: repeatInterval)) + referenceTimeInterval
  95. }
  96. /**
  97. Returns a slice of schedule items that occur between two dates
  98. - parameter startDate: The start date of the range
  99. - parameter endDate: The end date of the range
  100. - returns: A slice of `ScheduleItem` values
  101. */
  102. public func between(start startDate: Date, end endDate: Date) -> [AbsoluteScheduleValue<T>] {
  103. guard startDate <= endDate else {
  104. return []
  105. }
  106. let startOffset = scheduleOffset(for: startDate)
  107. let endOffset = startOffset + endDate.timeIntervalSince(startDate)
  108. guard endOffset <= maxTimeInterval else {
  109. let boundaryDate = startDate.addingTimeInterval(maxTimeInterval - startOffset)
  110. return between(start: startDate, end: boundaryDate) + between(start: boundaryDate, end: endDate)
  111. }
  112. var startIndex = 0
  113. var endIndex = items.count
  114. for (index, item) in items.enumerated() {
  115. if startOffset >= item.startTime {
  116. startIndex = index
  117. }
  118. if endOffset < item.startTime {
  119. endIndex = index
  120. break
  121. }
  122. }
  123. let referenceDate = startDate.addingTimeInterval(-startOffset)
  124. return (startIndex..<endIndex).map { (index) in
  125. let item = items[index]
  126. let endTime = index + 1 < items.count ? items[index + 1].startTime : maxTimeInterval
  127. return AbsoluteScheduleValue(
  128. startDate: referenceDate.addingTimeInterval(item.startTime),
  129. endDate: referenceDate.addingTimeInterval(endTime),
  130. value: item.value
  131. )
  132. }
  133. }
  134. public func map<U>(_ transform: (T) -> U) -> DailyValueSchedule<U> {
  135. return DailyValueSchedule<U>(
  136. dailyItems: items.map { $0.map(transform) },
  137. timeZone: timeZone
  138. )!
  139. }
  140. public static func zip<L, R>(_ lhs: DailyValueSchedule<L>, _ rhs: DailyValueSchedule<R>) -> DailyValueSchedule where T == (L, R) {
  141. precondition(lhs.timeZone == rhs.timeZone)
  142. var (leftCursor, rightCursor) = (lhs.items.startIndex, rhs.items.startIndex)
  143. var alignedItems: [RepeatingScheduleValue<(L, R)>] = []
  144. repeat {
  145. let (leftItem, rightItem) = (lhs.items[leftCursor], rhs.items[rightCursor])
  146. let alignedItem = RepeatingScheduleValue(
  147. startTime: max(leftItem.startTime, rightItem.startTime),
  148. value: (leftItem.value, rightItem.value)
  149. )
  150. alignedItems.append(alignedItem)
  151. let nextLeftStartTime = leftCursor == lhs.items.endIndex - 1 ? nil : lhs.items[leftCursor + 1].startTime
  152. let nextRightStartTime = rightCursor == rhs.items.endIndex - 1 ? nil : rhs.items[rightCursor + 1].startTime
  153. switch (nextLeftStartTime, nextRightStartTime) {
  154. case (.some(let leftStart), .some(let rightStart)):
  155. if leftStart < rightStart {
  156. leftCursor += 1
  157. } else if rightStart < leftStart {
  158. rightCursor += 1
  159. } else {
  160. leftCursor += 1
  161. rightCursor += 1
  162. }
  163. case (.some, .none):
  164. leftCursor += 1
  165. case (.none, .some):
  166. rightCursor += 1
  167. case (.none, .none):
  168. leftCursor += 1
  169. rightCursor += 1
  170. }
  171. } while leftCursor < lhs.items.endIndex && rightCursor < rhs.items.endIndex
  172. return DailyValueSchedule(dailyItems: alignedItems, timeZone: lhs.timeZone)!
  173. }
  174. }
  175. extension DailyValueSchedule: RawRepresentable, CustomDebugStringConvertible where T: RawRepresentable {
  176. public typealias RawValue = [String: Any]
  177. public init?(rawValue: RawValue) {
  178. guard let rawItems = rawValue["items"] as? [RepeatingScheduleValue<T>.RawValue] else {
  179. return nil
  180. }
  181. var timeZone: TimeZone?
  182. if let offset = rawValue["timeZone"] as? Int {
  183. timeZone = TimeZone(secondsFromGMT: offset)
  184. }
  185. let validScheduleItems = rawItems.compactMap(RepeatingScheduleValue<T>.init(rawValue:))
  186. guard validScheduleItems.count == rawItems.count else {
  187. return nil
  188. }
  189. self.init(dailyItems: validScheduleItems, timeZone: timeZone)
  190. }
  191. public var rawValue: RawValue {
  192. let rawItems = items.map { $0.rawValue }
  193. return [
  194. "timeZone": timeZone.secondsFromGMT(),
  195. "items": rawItems
  196. ]
  197. }
  198. public var debugDescription: String {
  199. return String(reflecting: rawValue)
  200. }
  201. }
  202. extension DailyValueSchedule: Codable where T: Codable {}
  203. extension DailyValueSchedule: Equatable where T: Equatable {}
  204. extension RepeatingScheduleValue {
  205. public static func == <L: Equatable, R: Equatable> (lhs: RepeatingScheduleValue, rhs: RepeatingScheduleValue) -> Bool where T == (L, R) {
  206. return lhs.startTime == rhs.startTime && lhs.value == rhs.value
  207. }
  208. }
  209. extension DailyValueSchedule {
  210. public static func == <L: Equatable, R: Equatable> (lhs: DailyValueSchedule, rhs: DailyValueSchedule) -> Bool where T == (L, R) {
  211. return lhs.timeZone == rhs.timeZone
  212. && lhs.items.count == rhs.items.count
  213. && Swift.zip(lhs.items, rhs.items).allSatisfy(==)
  214. }
  215. }