DailyValueSchedule.swift 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276
  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. let repeatInterval: TimeInterval
  72. public let items: [RepeatingScheduleValue<T>]
  73. public var timeZone: TimeZone
  74. public init?(dailyItems: [RepeatingScheduleValue<T>], timeZone: TimeZone? = nil) {
  75. self.repeatInterval = TimeInterval(hours: 24)
  76. self.items = dailyItems.sorted { $0.startTime < $1.startTime }
  77. self.timeZone = timeZone ?? TimeZone.currentFixed
  78. guard let firstItem = self.items.first else {
  79. return nil
  80. }
  81. referenceTimeInterval = firstItem.startTime
  82. }
  83. var maxTimeInterval: TimeInterval {
  84. return referenceTimeInterval + repeatInterval
  85. }
  86. /**
  87. Returns the time interval for a given date normalized to the span of the schedule items
  88. - parameter date: The date to convert
  89. */
  90. func scheduleOffset(for date: Date) -> TimeInterval {
  91. // The time interval since a reference date in the specified time zone
  92. let interval = date.timeIntervalSinceReferenceDate + TimeInterval(timeZone.secondsFromGMT(for: date))
  93. // The offset of the time interval since the last occurence of the reference time + n * repeatIntervals.
  94. // 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
  95. return ((interval - referenceTimeInterval).truncatingRemainder(dividingBy: repeatInterval)) + referenceTimeInterval
  96. }
  97. /**
  98. Returns a slice of schedule items that occur between two dates
  99. - parameter startDate: The start date of the range
  100. - parameter endDate: The end date of the range
  101. - returns: A slice of `ScheduleItem` values
  102. */
  103. public func between(start startDate: Date, end endDate: Date) -> [AbsoluteScheduleValue<T>] {
  104. guard startDate <= endDate else {
  105. return []
  106. }
  107. let startOffset = scheduleOffset(for: startDate)
  108. let endOffset = startOffset + endDate.timeIntervalSince(startDate)
  109. guard endOffset <= maxTimeInterval else {
  110. let boundaryDate = startDate.addingTimeInterval(maxTimeInterval - startOffset)
  111. return between(start: startDate, end: boundaryDate) + between(start: boundaryDate, end: endDate)
  112. }
  113. var startIndex = 0
  114. var endIndex = items.count
  115. for (index, item) in items.enumerated() {
  116. if startOffset >= item.startTime {
  117. startIndex = index
  118. }
  119. if endOffset < item.startTime {
  120. endIndex = index
  121. break
  122. }
  123. }
  124. let referenceDate = startDate.addingTimeInterval(-startOffset)
  125. return (startIndex..<endIndex).map { (index) in
  126. let item = items[index]
  127. let endTime = index + 1 < items.count ? items[index + 1].startTime : maxTimeInterval
  128. return AbsoluteScheduleValue(
  129. startDate: referenceDate.addingTimeInterval(item.startTime),
  130. endDate: referenceDate.addingTimeInterval(endTime),
  131. value: item.value
  132. )
  133. }
  134. }
  135. public func map<U>(_ transform: (T) -> U) -> DailyValueSchedule<U> {
  136. return DailyValueSchedule<U>(
  137. dailyItems: items.map { $0.map(transform) },
  138. timeZone: timeZone
  139. )!
  140. }
  141. public static func zip<L, R>(_ lhs: DailyValueSchedule<L>, _ rhs: DailyValueSchedule<R>) -> DailyValueSchedule where T == (L, R) {
  142. precondition(lhs.timeZone == rhs.timeZone)
  143. var (leftCursor, rightCursor) = (lhs.items.startIndex, rhs.items.startIndex)
  144. var alignedItems: [RepeatingScheduleValue<(L, R)>] = []
  145. repeat {
  146. let (leftItem, rightItem) = (lhs.items[leftCursor], rhs.items[rightCursor])
  147. let alignedItem = RepeatingScheduleValue(
  148. startTime: max(leftItem.startTime, rightItem.startTime),
  149. value: (leftItem.value, rightItem.value)
  150. )
  151. alignedItems.append(alignedItem)
  152. let nextLeftStartTime = leftCursor == lhs.items.endIndex - 1 ? nil : lhs.items[leftCursor + 1].startTime
  153. let nextRightStartTime = rightCursor == rhs.items.endIndex - 1 ? nil : rhs.items[rightCursor + 1].startTime
  154. switch (nextLeftStartTime, nextRightStartTime) {
  155. case (.some(let leftStart), .some(let rightStart)):
  156. if leftStart < rightStart {
  157. leftCursor += 1
  158. } else if rightStart < leftStart {
  159. rightCursor += 1
  160. } else {
  161. leftCursor += 1
  162. rightCursor += 1
  163. }
  164. case (.some, .none):
  165. leftCursor += 1
  166. case (.none, .some):
  167. rightCursor += 1
  168. case (.none, .none):
  169. leftCursor += 1
  170. rightCursor += 1
  171. }
  172. } while leftCursor < lhs.items.endIndex && rightCursor < rhs.items.endIndex
  173. return DailyValueSchedule(dailyItems: alignedItems, timeZone: lhs.timeZone)!
  174. }
  175. }
  176. extension DailyValueSchedule: RawRepresentable, CustomDebugStringConvertible where T: RawRepresentable {
  177. public typealias RawValue = [String: Any]
  178. public init?(rawValue: RawValue) {
  179. guard let rawItems = rawValue["items"] as? [RepeatingScheduleValue<T>.RawValue] else {
  180. return nil
  181. }
  182. var timeZone: TimeZone?
  183. if let offset = rawValue["timeZone"] as? Int {
  184. timeZone = TimeZone(secondsFromGMT: offset)
  185. }
  186. let validScheduleItems = rawItems.compactMap(RepeatingScheduleValue<T>.init(rawValue:))
  187. guard validScheduleItems.count == rawItems.count else {
  188. return nil
  189. }
  190. self.init(dailyItems: validScheduleItems, timeZone: timeZone)
  191. }
  192. public var rawValue: RawValue {
  193. let rawItems = items.map { $0.rawValue }
  194. return [
  195. "timeZone": timeZone.secondsFromGMT(),
  196. "items": rawItems
  197. ]
  198. }
  199. public var debugDescription: String {
  200. return String(reflecting: rawValue)
  201. }
  202. }
  203. extension DailyValueSchedule: Codable where T: Codable {}
  204. extension DailyValueSchedule: Equatable where T: Equatable {}
  205. extension RepeatingScheduleValue {
  206. public static func == <L: Equatable, R: Equatable> (lhs: RepeatingScheduleValue, rhs: RepeatingScheduleValue) -> Bool where T == (L, R) {
  207. return lhs.startTime == rhs.startTime && lhs.value == rhs.value
  208. }
  209. }
  210. extension DailyValueSchedule {
  211. public static func == <L: Equatable, R: Equatable> (lhs: DailyValueSchedule, rhs: DailyValueSchedule) -> Bool where T == (L, R) {
  212. return lhs.timeZone == rhs.timeZone
  213. && lhs.items.count == rhs.items.count
  214. && Swift.zip(lhs.items, rhs.items).allSatisfy(==)
  215. }
  216. }