MainChartView.swift 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798
  1. import Algorithms
  2. import SwiftDate
  3. import SwiftUI
  4. private enum PredictionType: Hashable {
  5. case iob
  6. case cob
  7. case zt
  8. case uam
  9. }
  10. struct DotInfo {
  11. let rect: CGRect
  12. let value: Decimal
  13. }
  14. typealias GlucoseYRange = (minValue: Int, minY: CGFloat, maxValue: Int, maxY: CGFloat)
  15. struct MainChartView: View {
  16. private enum Config {
  17. static let endID = "End"
  18. static let screenHours = 5
  19. static let basalHeight: CGFloat = 120
  20. static let topYPadding: CGFloat = 20
  21. static let bottomYPadding: CGFloat = 50
  22. static let minAdditionalWidth: CGFloat = 150
  23. static let maxGlucose = 450
  24. static let minGlucose = 70
  25. static let yLinesCount = 5
  26. static let bolusSize: CGFloat = 8
  27. static let bolusScale: CGFloat = 3
  28. static let carbsSize: CGFloat = 10
  29. static let carbsScale: CGFloat = 0.3
  30. }
  31. @Binding var glucose: [BloodGlucose]
  32. @Binding var suggestion: Suggestion?
  33. @Binding var tempBasals: [PumpHistoryEvent]
  34. @Binding var boluses: [PumpHistoryEvent]
  35. @Binding var hours: Int
  36. @Binding var maxBasal: Decimal
  37. @Binding var basalProfile: [BasalProfileEntry]
  38. @Binding var tempTargets: [TempTarget]
  39. @Binding var carbs: [CarbsEntry]
  40. @Binding var timerDate: Date
  41. let units: GlucoseUnits
  42. @State var didAppearTrigger = false
  43. @State private var glucoseDots: [CGRect] = []
  44. @State private var predictionDots: [PredictionType: [CGRect]] = [:]
  45. @State private var bolusDots: [DotInfo] = []
  46. @State private var bolusPath = Path()
  47. @State private var tempBasalPath = Path()
  48. @State private var regularBasalPath = Path()
  49. @State private var tempTargetsPath = Path()
  50. @State private var carbsDots: [DotInfo] = []
  51. @State private var carbsPath = Path()
  52. @State private var glucoseYGange: GlucoseYRange = (0, 0, 0, 0)
  53. @State private var offset: CGFloat = 0
  54. @State private var cachedMaxBasalRate: Decimal?
  55. private let calculationQueue = DispatchQueue(label: "MainChartView.calculationQueue")
  56. private var dateDormatter: DateFormatter {
  57. let formatter = DateFormatter()
  58. formatter.timeStyle = .short
  59. return formatter
  60. }
  61. private var glucoseFormatter: NumberFormatter {
  62. let formatter = NumberFormatter()
  63. formatter.numberStyle = .decimal
  64. formatter.maximumFractionDigits = 1
  65. return formatter
  66. }
  67. private var bolusFormatter: NumberFormatter {
  68. let formatter = NumberFormatter()
  69. formatter.numberStyle = .decimal
  70. formatter.minimumIntegerDigits = 0
  71. formatter.maximumFractionDigits = 2
  72. formatter.decimalSeparator = "."
  73. return formatter
  74. }
  75. private var carbsFormatter: NumberFormatter {
  76. let formatter = NumberFormatter()
  77. formatter.numberStyle = .decimal
  78. formatter.maximumFractionDigits = 0
  79. return formatter
  80. }
  81. // MARK: - Views
  82. var body: some View {
  83. GeometryReader { geo in
  84. ZStack(alignment: .leading) {
  85. yGridView(fullSize: geo.size)
  86. mainScrollView(fullSize: geo.size)
  87. glucoseLabelsView(fullSize: geo.size)
  88. }
  89. }
  90. }
  91. private func mainScrollView(fullSize: CGSize) -> some View {
  92. ScrollView(.horizontal, showsIndicators: false) {
  93. ScrollViewReader { scroll in
  94. ZStack(alignment: .top) {
  95. tempTargetsView(fullSize: fullSize).drawingGroup()
  96. basalView(fullSize: fullSize).drawingGroup()
  97. mainView(fullSize: fullSize).id(Config.endID)
  98. .drawingGroup()
  99. .onChange(of: glucose) { _ in
  100. scroll.scrollTo(Config.endID, anchor: .trailing)
  101. }
  102. .onChange(of: suggestion) { _ in
  103. scroll.scrollTo(Config.endID, anchor: .trailing)
  104. }
  105. .onChange(of: tempBasals) { _ in
  106. scroll.scrollTo(Config.endID, anchor: .trailing)
  107. }
  108. .onAppear {
  109. // add trigger to the end of main queue
  110. DispatchQueue.main.async {
  111. scroll.scrollTo(Config.endID, anchor: .trailing)
  112. didAppearTrigger = true
  113. }
  114. }
  115. }
  116. }
  117. }
  118. }
  119. private func yGridView(fullSize: CGSize) -> some View {
  120. Path { path in
  121. let range = glucoseYGange
  122. let step = (range.maxY - range.minY) / CGFloat(Config.yLinesCount)
  123. for line in 0 ... Config.yLinesCount {
  124. path.move(to: CGPoint(x: 0, y: range.minY + CGFloat(line) * step))
  125. path.addLine(to: CGPoint(x: fullSize.width, y: range.minY + CGFloat(line) * step))
  126. }
  127. }.stroke(Color.secondary, lineWidth: 0.2)
  128. }
  129. private func glucoseLabelsView(fullSize: CGSize) -> some View {
  130. ForEach(0 ..< Config.yLinesCount + 1) { line -> AnyView in
  131. let range = glucoseYGange
  132. let yStep = (range.maxY - range.minY) / CGFloat(Config.yLinesCount)
  133. let valueStep = Double(range.maxValue - range.minValue) / Double(Config.yLinesCount)
  134. let value = round(Double(range.maxValue) - Double(line) * valueStep) *
  135. (units == .mmolL ? Double(GlucoseUnits.exchangeRate) : 1)
  136. return Text(glucoseFormatter.string(from: value as NSNumber)!)
  137. .position(CGPoint(x: fullSize.width - 12, y: range.minY + CGFloat(line) * yStep))
  138. .font(.caption2)
  139. .asAny()
  140. }
  141. }
  142. private func basalView(fullSize: CGSize) -> some View {
  143. ZStack {
  144. tempBasalPath.fill(Color.tempBasal.opacity(0.5)).scaleEffect(x: 1, y: -1)
  145. // tempBasalPath.stroke(Color.tempBasal, lineWidth: 1).scaleEffect(x: 1, y: -1) // removed the Y=0 line, not needed when having icicles
  146. regularBasalPath.stroke(Color.tempBasal, style: StrokeStyle(lineWidth: 1, dash: [3])).scaleEffect(x: 1, y: -1)
  147. }
  148. .frame(width: fullGlucoseWidth(viewWidth: fullSize.width) + additionalWidth(viewWidth: fullSize.width))
  149. .frame(maxHeight: Config.basalHeight)
  150. // .background(Color.secondary.opacity(0.1))
  151. .onChange(of: tempBasals) { _ in
  152. calculateBasalPoints(fullSize: fullSize)
  153. }
  154. .onChange(of: maxBasal) { _ in
  155. calculateBasalPoints(fullSize: fullSize)
  156. }
  157. .onChange(of: basalProfile) { _ in
  158. calculateBasalPoints(fullSize: fullSize)
  159. }
  160. .onChange(of: didAppearTrigger) { _ in
  161. calculateBasalPoints(fullSize: fullSize)
  162. }
  163. }
  164. private func mainView(fullSize: CGSize) -> some View {
  165. Group {
  166. VStack {
  167. ZStack {
  168. xGridView(fullSize: fullSize)
  169. carbsView(fullSize: fullSize)
  170. bolusView(fullSize: fullSize)
  171. glucoseView(fullSize: fullSize)
  172. predictionsView(fullSize: fullSize)
  173. }
  174. timeLabelsView(fullSize: fullSize)
  175. }
  176. }
  177. .frame(width: fullGlucoseWidth(viewWidth: fullSize.width) + additionalWidth(viewWidth: fullSize.width))
  178. }
  179. @Environment(\.colorScheme) var colorScheme
  180. private func xGridView(fullSize: CGSize) -> some View {
  181. ZStack {
  182. Path { path in
  183. for hour in 0 ..< hours + hours {
  184. let x = firstHourPosition(viewWidth: fullSize.width) +
  185. oneSecondStep(viewWidth: fullSize.width) *
  186. CGFloat(hour) * CGFloat(1.hours.timeInterval)
  187. path.move(to: CGPoint(x: x, y: 0))
  188. path.addLine(to: CGPoint(x: x, y: fullSize.height - 20))
  189. }
  190. }
  191. .stroke(Color.secondary, lineWidth: 0.2)
  192. Path { path in
  193. let x = timeToXCoordinate(timerDate.timeIntervalSince1970, fullSize: fullSize)
  194. path.move(to: CGPoint(x: x, y: 0))
  195. path.addLine(to: CGPoint(x: x, y: fullSize.height - 20))
  196. }
  197. .stroke(
  198. colorScheme == .dark ? Color.white : Color.black, // current time as vertical line
  199. style: StrokeStyle(lineWidth: 0.5, dash: [2])
  200. )
  201. }
  202. }
  203. private func timeLabelsView(fullSize: CGSize) -> some View {
  204. ZStack {
  205. // X time labels
  206. ForEach(0 ..< hours + hours) { hour in
  207. Text(dateDormatter.string(from: firstHourDate().addingTimeInterval(hour.hours.timeInterval)))
  208. .font(.caption)
  209. .position(
  210. x: firstHourPosition(viewWidth: fullSize.width) +
  211. oneSecondStep(viewWidth: fullSize.width) *
  212. CGFloat(hour) * CGFloat(1.hours.timeInterval),
  213. y: 10.0
  214. )
  215. .foregroundColor(.secondary)
  216. }
  217. }.frame(maxHeight: 20)
  218. }
  219. private func glucoseView(fullSize: CGSize) -> some View {
  220. Path { path in
  221. for rect in glucoseDots {
  222. path.addEllipse(in: rect)
  223. }
  224. }
  225. .fill(Color.loopGreen)
  226. .onChange(of: glucose) { _ in
  227. update(fullSize: fullSize)
  228. }
  229. .onChange(of: didAppearTrigger) { _ in
  230. update(fullSize: fullSize)
  231. }
  232. .onReceive(Foundation.NotificationCenter.default.publisher(for: UIApplication.willEnterForegroundNotification)) { _ in
  233. update(fullSize: fullSize)
  234. }
  235. }
  236. private func bolusView(fullSize: CGSize) -> some View {
  237. ZStack {
  238. bolusPath
  239. .fill(Color.insulin)
  240. bolusPath
  241. .stroke(Color.primary, lineWidth: 0.5)
  242. ForEach(bolusDots, id: \.rect.minX) { info -> AnyView in
  243. let position = CGPoint(x: info.rect.midX, y: info.rect.maxY + 8)
  244. return Text(bolusFormatter.string(from: info.value as NSNumber)!).font(.caption2)
  245. .position(position)
  246. .asAny()
  247. }
  248. }
  249. .onChange(of: boluses) { _ in
  250. calculateBolusDots(fullSize: fullSize)
  251. }
  252. .onChange(of: didAppearTrigger) { _ in
  253. calculateBolusDots(fullSize: fullSize)
  254. }
  255. }
  256. private func carbsView(fullSize: CGSize) -> some View {
  257. ZStack {
  258. carbsPath
  259. .fill(Color.loopYellow)
  260. carbsPath
  261. .stroke(Color.primary, lineWidth: 0.5)
  262. ForEach(carbsDots, id: \.rect.minX) { info -> AnyView in
  263. let position = CGPoint(x: info.rect.midX, y: info.rect.minY - 8)
  264. return Text(carbsFormatter.string(from: info.value as NSNumber)!).font(.caption2)
  265. .position(position)
  266. .asAny()
  267. }
  268. }
  269. .onChange(of: carbs) { _ in
  270. calculateCarbsDots(fullSize: fullSize)
  271. }
  272. .onChange(of: didAppearTrigger) { _ in
  273. calculateCarbsDots(fullSize: fullSize)
  274. }
  275. }
  276. private func tempTargetsView(fullSize: CGSize) -> some View {
  277. ZStack {
  278. tempTargetsPath
  279. .fill(Color.tempBasal.opacity(0.5))
  280. }
  281. .onChange(of: glucose) { _ in
  282. calculateTempTargetsRects(fullSize: fullSize)
  283. }
  284. .onChange(of: tempTargets) { _ in
  285. calculateTempTargetsRects(fullSize: fullSize)
  286. }
  287. .onChange(of: didAppearTrigger) { _ in
  288. calculateTempTargetsRects(fullSize: fullSize)
  289. }
  290. }
  291. private func predictionsView(fullSize: CGSize) -> some View {
  292. Group {
  293. Path { path in
  294. for rect in predictionDots[.iob] ?? [] {
  295. path.addEllipse(in: rect)
  296. }
  297. }.fill(Color.insulin)
  298. Path { path in
  299. for rect in predictionDots[.cob] ?? [] {
  300. path.addEllipse(in: rect)
  301. }
  302. }.fill(Color.loopYellow)
  303. Path { path in
  304. for rect in predictionDots[.zt] ?? [] {
  305. path.addEllipse(in: rect)
  306. }
  307. }.fill(Color.zt)
  308. Path { path in
  309. for rect in predictionDots[.uam] ?? [] {
  310. path.addEllipse(in: rect)
  311. }
  312. }.fill(Color.uam)
  313. }
  314. .onChange(of: suggestion) { _ in
  315. update(fullSize: fullSize)
  316. }
  317. }
  318. }
  319. // MARK: - Calculations
  320. extension MainChartView {
  321. private func update(fullSize: CGSize) {
  322. calculatePredictionDots(fullSize: fullSize, type: .iob)
  323. calculatePredictionDots(fullSize: fullSize, type: .cob)
  324. calculatePredictionDots(fullSize: fullSize, type: .zt)
  325. calculatePredictionDots(fullSize: fullSize, type: .uam)
  326. calculateGlucoseDots(fullSize: fullSize)
  327. calculateBolusDots(fullSize: fullSize)
  328. calculateCarbsDots(fullSize: fullSize)
  329. calculateTempTargetsRects(fullSize: fullSize)
  330. calculateTempTargetsRects(fullSize: fullSize)
  331. calculateBasalPoints(fullSize: fullSize)
  332. }
  333. private func calculateGlucoseDots(fullSize: CGSize) {
  334. calculationQueue.async {
  335. let dots = glucose.concurrentMap { value -> CGRect in
  336. let position = glucoseToCoordinate(value, fullSize: fullSize)
  337. return CGRect(x: position.x - 2, y: position.y - 2, width: 4, height: 4)
  338. }
  339. let range = self.getGlucoseYRange(fullSize: fullSize)
  340. DispatchQueue.main.async {
  341. glucoseYGange = range
  342. glucoseDots = dots
  343. }
  344. }
  345. }
  346. private func calculateBolusDots(fullSize: CGSize) {
  347. calculationQueue.async {
  348. let dots = boluses.map { value -> DotInfo in
  349. let center = timeToInterpolatedPoint(value.timestamp.timeIntervalSince1970, fullSize: fullSize)
  350. let size = Config.bolusSize + CGFloat(value.amount ?? 0) * Config.bolusScale
  351. let rect = CGRect(x: center.x - size / 2, y: center.y - size / 2, width: size, height: size)
  352. return DotInfo(rect: rect, value: value.amount ?? 0)
  353. }
  354. let path = Path { path in
  355. for dot in dots {
  356. path.addEllipse(in: dot.rect)
  357. }
  358. }
  359. DispatchQueue.main.async {
  360. bolusDots = dots
  361. bolusPath = path
  362. }
  363. }
  364. }
  365. private func calculateCarbsDots(fullSize: CGSize) {
  366. calculationQueue.async {
  367. let dots = carbs.map { value -> DotInfo in
  368. let center = timeToInterpolatedPoint(value.createdAt.timeIntervalSince1970, fullSize: fullSize)
  369. let size = Config.carbsSize + CGFloat(value.carbs) * Config.carbsScale
  370. let rect = CGRect(x: center.x - size / 2, y: center.y - size / 2, width: size, height: size)
  371. return DotInfo(rect: rect, value: value.carbs)
  372. }
  373. let path = Path { path in
  374. for dot in dots {
  375. path.addEllipse(in: dot.rect)
  376. }
  377. }
  378. DispatchQueue.main.async {
  379. carbsDots = dots
  380. carbsPath = path
  381. }
  382. }
  383. }
  384. private func calculatePredictionDots(fullSize: CGSize, type: PredictionType) {
  385. calculationQueue.async {
  386. let values: [Int] = { () -> [Int] in
  387. switch type {
  388. case .iob:
  389. return suggestion?.predictions?.iob ?? []
  390. case .cob:
  391. return suggestion?.predictions?.cob ?? []
  392. case .zt:
  393. return suggestion?.predictions?.zt ?? []
  394. case .uam:
  395. return suggestion?.predictions?.uam ?? []
  396. }
  397. }()
  398. var index = 0
  399. let dots = values.map { value -> CGRect in
  400. let position = predictionToCoordinate(value, fullSize: fullSize, index: index)
  401. index += 1
  402. return CGRect(x: position.x - 2, y: position.y - 2, width: 4, height: 4)
  403. }
  404. DispatchQueue.main.async {
  405. predictionDots[type] = dots
  406. }
  407. }
  408. }
  409. private func calculateBasalPoints(fullSize: CGSize) {
  410. calculationQueue.async {
  411. self.cachedMaxBasalRate = nil
  412. let dayAgoTime = Date().addingTimeInterval(-1.days.timeInterval).timeIntervalSince1970
  413. let firstTempTime = (tempBasals.first?.timestamp ?? Date()).timeIntervalSince1970
  414. var lastTimeEnd = firstTempTime
  415. let firstRegularBasalPoints = findRegularBasalPoints(
  416. timeBegin: dayAgoTime,
  417. timeEnd: firstTempTime,
  418. fullSize: fullSize
  419. )
  420. let tempBasalPoints = firstRegularBasalPoints + tempBasals.chunks(ofCount: 2).map { chunk -> [CGPoint] in
  421. let chunk = Array(chunk)
  422. guard chunk.count == 2, chunk[0].type == .tempBasal, chunk[1].type == .tempBasalDuration else { return [] }
  423. let timeBegin = chunk[0].timestamp.timeIntervalSince1970
  424. let timeEnd = timeBegin + (chunk[1].durationMin ?? 0).minutes.timeInterval
  425. let rateCost = Config.basalHeight / CGFloat(maxBasalRate())
  426. let x0 = timeToXCoordinate(timeBegin, fullSize: fullSize)
  427. let y0 = Config.basalHeight - CGFloat(chunk[0].rate ?? 0) * rateCost
  428. let regularPoints = findRegularBasalPoints(timeBegin: lastTimeEnd, timeEnd: timeBegin, fullSize: fullSize)
  429. lastTimeEnd = timeEnd
  430. return regularPoints + [CGPoint(x: x0, y: y0)]
  431. }.flatMap { $0 }
  432. let tempBasalPath = Path { path in
  433. var yPoint: CGFloat = Config.basalHeight
  434. path.move(to: CGPoint(x: 0, y: yPoint))
  435. for point in tempBasalPoints {
  436. path.addLine(to: CGPoint(x: point.x, y: yPoint))
  437. path.addLine(to: point)
  438. yPoint = point.y
  439. }
  440. let lastPoint = lastBasalPoint(fullSize: fullSize)
  441. path.addLine(to: CGPoint(x: lastPoint.x, y: yPoint))
  442. path.addLine(to: CGPoint(x: lastPoint.x, y: Config.basalHeight))
  443. path.addLine(to: CGPoint(x: 0, y: Config.basalHeight))
  444. }
  445. let endDateTime = dayAgoTime + 1.days.timeInterval + 6.hours.timeInterval
  446. let regularBasalPoints = findRegularBasalPoints(
  447. timeBegin: dayAgoTime,
  448. timeEnd: endDateTime,
  449. fullSize: fullSize
  450. )
  451. let regularBasalPath = Path { path in
  452. var yPoint: CGFloat = Config.basalHeight
  453. path.move(to: CGPoint(x: -50, y: yPoint))
  454. for point in regularBasalPoints {
  455. path.addLine(to: CGPoint(x: point.x, y: yPoint))
  456. path.addLine(to: point)
  457. yPoint = point.y
  458. }
  459. path.addLine(to: CGPoint(x: timeToXCoordinate(endDateTime, fullSize: fullSize), y: yPoint))
  460. }
  461. DispatchQueue.main.async {
  462. self.tempBasalPath = tempBasalPath
  463. self.regularBasalPath = regularBasalPath
  464. }
  465. }
  466. }
  467. private func maxBasalRate() -> Decimal {
  468. if let cached = cachedMaxBasalRate {
  469. return cached
  470. }
  471. cachedMaxBasalRate = tempBasals.compactMap(\.rate).max() ?? maxBasal
  472. return cachedMaxBasalRate!
  473. }
  474. private func calculateTempTargetsRects(fullSize: CGSize) {
  475. calculationQueue.async {
  476. var rects = tempTargets.map { tempTarget -> CGRect in
  477. let x0 = timeToXCoordinate(tempTarget.createdAt.timeIntervalSince1970, fullSize: fullSize)
  478. let y0 = glucoseToYCoordinate(Int(tempTarget.targetTop ?? 0), fullSize: fullSize)
  479. let x1 = timeToXCoordinate(
  480. tempTarget.createdAt.timeIntervalSince1970 + Int(tempTarget.duration).minutes.timeInterval,
  481. fullSize: fullSize
  482. )
  483. let y1 = glucoseToYCoordinate(Int(tempTarget.targetBottom ?? 0), fullSize: fullSize)
  484. return CGRect(
  485. x: x0,
  486. y: y0 - 3,
  487. width: x1 - x0,
  488. height: y1 - y0 + 6
  489. )
  490. }
  491. if rects.count > 1 {
  492. rects = rects.reduce([]) { result, rect -> [CGRect] in
  493. guard var last = result.last else { return [rect] }
  494. if last.origin.x + last.width > rect.origin.x {
  495. last.size.width = rect.origin.x - last.origin.x
  496. }
  497. var res = Array(result.dropLast())
  498. res.append(contentsOf: [last, rect])
  499. return res
  500. }
  501. }
  502. let path = Path { path in
  503. path.addRects(rects)
  504. }
  505. DispatchQueue.main.async {
  506. tempTargetsPath = path
  507. }
  508. }
  509. }
  510. private func findRegularBasalPoints(timeBegin: TimeInterval, timeEnd: TimeInterval, fullSize: CGSize) -> [CGPoint] {
  511. guard timeBegin < timeEnd else {
  512. return []
  513. }
  514. let beginDate = Date(timeIntervalSince1970: timeBegin)
  515. let calendar = Calendar.current
  516. let startOfDay = calendar.startOfDay(for: beginDate)
  517. let basalNormalized = basalProfile.map {
  518. (
  519. time: startOfDay.addingTimeInterval($0.minutes.minutes.timeInterval).timeIntervalSince1970,
  520. rate: $0.rate
  521. )
  522. } + basalProfile.map {
  523. (
  524. time: startOfDay.addingTimeInterval($0.minutes.minutes.timeInterval + 1.days.timeInterval).timeIntervalSince1970,
  525. rate: $0.rate
  526. )
  527. } + basalProfile.map {
  528. (
  529. time: startOfDay.addingTimeInterval($0.minutes.minutes.timeInterval + 2.days.timeInterval).timeIntervalSince1970,
  530. rate: $0.rate
  531. )
  532. }
  533. let basalTruncatedPoints = basalNormalized.windows(ofCount: 2)
  534. .compactMap { window -> CGPoint? in
  535. let window = Array(window)
  536. if window[0].time < timeBegin, window[1].time < timeBegin {
  537. return nil
  538. }
  539. let rateCost = Config.basalHeight / CGFloat(maxBasalRate())
  540. if window[0].time < timeBegin, window[1].time >= timeBegin {
  541. let x = timeToXCoordinate(timeBegin, fullSize: fullSize)
  542. let y = Config.basalHeight - CGFloat(window[0].rate) * rateCost
  543. return CGPoint(x: x, y: y)
  544. }
  545. if window[0].time >= timeBegin, window[0].time < timeEnd {
  546. let x = timeToXCoordinate(window[0].time, fullSize: fullSize)
  547. let y = Config.basalHeight - CGFloat(window[0].rate) * rateCost
  548. return CGPoint(x: x, y: y)
  549. }
  550. return nil
  551. }
  552. return basalTruncatedPoints
  553. }
  554. private func lastBasalPoint(fullSize: CGSize) -> CGPoint {
  555. let lastBasal = Array(tempBasals.suffix(2))
  556. guard lastBasal.count == 2 else {
  557. return CGPoint(x: timeToXCoordinate(Date().timeIntervalSince1970, fullSize: fullSize), y: Config.basalHeight)
  558. }
  559. let endBasalTime = lastBasal[0].timestamp.timeIntervalSince1970 + (lastBasal[1].durationMin?.minutes.timeInterval ?? 0)
  560. let rateCost = Config.basalHeight / CGFloat(maxBasalRate())
  561. let x = timeToXCoordinate(endBasalTime, fullSize: fullSize)
  562. let y = Config.basalHeight - CGFloat(lastBasal[0].rate ?? 0) * rateCost
  563. return CGPoint(x: x, y: y)
  564. }
  565. private func fullGlucoseWidth(viewWidth: CGFloat) -> CGFloat {
  566. viewWidth * CGFloat(hours) / CGFloat(Config.screenHours)
  567. }
  568. private func additionalWidth(viewWidth: CGFloat) -> CGFloat {
  569. guard let predictions = suggestion?.predictions,
  570. let deliveredAt = suggestion?.deliverAt,
  571. let last = glucose.last
  572. else {
  573. return Config.minAdditionalWidth
  574. }
  575. let iob = predictions.iob?.count ?? 0
  576. let zt = predictions.zt?.count ?? 0
  577. let cob = predictions.cob?.count ?? 0
  578. let uam = predictions.uam?.count ?? 0
  579. let max = [iob, zt, cob, uam].max() ?? 0
  580. let lastDeltaTime = last.dateString.timeIntervalSince(deliveredAt)
  581. let additionalTime = CGFloat(TimeInterval(max) * 5.minutes.timeInterval - lastDeltaTime)
  582. let oneSecondWidth = oneSecondStep(viewWidth: viewWidth)
  583. return Swift.max(additionalTime * oneSecondWidth, Config.minAdditionalWidth)
  584. }
  585. private func oneSecondStep(viewWidth: CGFloat) -> CGFloat {
  586. viewWidth / (CGFloat(Config.screenHours) * CGFloat(1.hours.timeInterval))
  587. }
  588. private func maxPredValue() -> Int? {
  589. [
  590. suggestion?.predictions?.cob ?? [],
  591. suggestion?.predictions?.iob ?? [],
  592. suggestion?.predictions?.zt ?? [],
  593. suggestion?.predictions?.uam ?? []
  594. ]
  595. .flatMap { $0 }
  596. .max()
  597. }
  598. private func minPredValue() -> Int? {
  599. [
  600. suggestion?.predictions?.cob ?? [],
  601. suggestion?.predictions?.iob ?? [],
  602. suggestion?.predictions?.zt ?? [],
  603. suggestion?.predictions?.uam ?? []
  604. ]
  605. .flatMap { $0 }
  606. .min()
  607. }
  608. private func maxTargetValue() -> Int? {
  609. tempTargets.map { $0.targetTop ?? 0 }.filter { $0 > 0 }.max().map(Int.init)
  610. }
  611. private func minTargetValue() -> Int? {
  612. tempTargets.map { $0.targetBottom ?? 0 }.filter { $0 > 0 }.min().map(Int.init)
  613. }
  614. private func glucoseToCoordinate(_ glucoseEntry: BloodGlucose, fullSize: CGSize) -> CGPoint {
  615. let x = timeToXCoordinate(glucoseEntry.dateString.timeIntervalSince1970, fullSize: fullSize)
  616. let y = glucoseToYCoordinate(glucoseEntry.glucose ?? 0, fullSize: fullSize)
  617. return CGPoint(x: x, y: y)
  618. }
  619. private func predictionToCoordinate(_ pred: Int, fullSize: CGSize, index: Int) -> CGPoint {
  620. guard let deliveredAt = suggestion?.deliverAt else {
  621. return .zero
  622. }
  623. let predTime = deliveredAt.timeIntervalSince1970 + TimeInterval(index) * 5.minutes.timeInterval
  624. let x = timeToXCoordinate(predTime, fullSize: fullSize)
  625. let y = glucoseToYCoordinate(pred, fullSize: fullSize)
  626. return CGPoint(x: x, y: y)
  627. }
  628. private func timeToXCoordinate(_ time: TimeInterval, fullSize: CGSize) -> CGFloat {
  629. let xOffset = -(
  630. glucose.first?.dateString.timeIntervalSince1970 ?? Date()
  631. .addingTimeInterval(-1.days.timeInterval).timeIntervalSince1970
  632. )
  633. let stepXFraction = fullGlucoseWidth(viewWidth: fullSize.width) / CGFloat(hours.hours.timeInterval)
  634. let x = CGFloat(time + xOffset) * stepXFraction
  635. return x
  636. }
  637. private func glucoseToYCoordinate(_ glucoseValue: Int, fullSize: CGSize) -> CGFloat {
  638. let topYPaddint = Config.topYPadding + Config.basalHeight
  639. let bottomYPadding = Config.bottomYPadding
  640. let (minValue, maxValue) = minMaxYValues()
  641. let stepYFraction = (fullSize.height - topYPaddint - bottomYPadding) / CGFloat(maxValue - minValue)
  642. let yOffset = CGFloat(minValue) * stepYFraction
  643. let y = fullSize.height - CGFloat(glucoseValue) * stepYFraction + yOffset - bottomYPadding
  644. return y
  645. }
  646. private func timeToInterpolatedPoint(_ time: TimeInterval, fullSize: CGSize) -> CGPoint {
  647. var nextIndex = 0
  648. for (index, value) in glucose.enumerated() {
  649. if value.dateString.timeIntervalSince1970 > time {
  650. nextIndex = index
  651. break
  652. }
  653. }
  654. let x = timeToXCoordinate(time, fullSize: fullSize)
  655. guard nextIndex > 0 else {
  656. let lastY = glucoseToYCoordinate(glucose.last?.glucose ?? 0, fullSize: fullSize)
  657. return CGPoint(x: x, y: lastY)
  658. }
  659. let prevX = timeToXCoordinate(glucose[nextIndex - 1].dateString.timeIntervalSince1970, fullSize: fullSize)
  660. let prevY = glucoseToYCoordinate(glucose[nextIndex - 1].glucose ?? 0, fullSize: fullSize)
  661. let nextX = timeToXCoordinate(glucose[nextIndex].dateString.timeIntervalSince1970, fullSize: fullSize)
  662. let nextY = glucoseToYCoordinate(glucose[nextIndex].glucose ?? 0, fullSize: fullSize)
  663. let delta = nextX - prevX
  664. let fraction = (x - prevX) / delta
  665. return pointInLine(CGPoint(x: prevX, y: prevY), CGPoint(x: nextX, y: nextY), fraction)
  666. }
  667. private func minMaxYValues() -> (min: Int, max: Int) {
  668. var maxValue = glucose.compactMap(\.glucose).max() ?? Config.maxGlucose
  669. if let maxPredValue = maxPredValue() {
  670. maxValue = max(maxValue, maxPredValue)
  671. }
  672. if let maxTargetValue = maxTargetValue() {
  673. maxValue = max(maxValue, maxTargetValue)
  674. }
  675. var minValue = glucose.compactMap(\.glucose).min() ?? Config.minGlucose
  676. if let minPredValue = minPredValue() {
  677. minValue = min(minValue, minPredValue)
  678. }
  679. if let minTargetValue = minTargetValue() {
  680. minValue = min(minValue, minTargetValue)
  681. }
  682. return (min: minValue, max: maxValue)
  683. }
  684. private func getGlucoseYRange(fullSize: CGSize) -> GlucoseYRange {
  685. let topYPaddint = Config.topYPadding + Config.basalHeight
  686. let bottomYPadding = Config.bottomYPadding
  687. let (minValue, maxValue) = minMaxYValues()
  688. let stepYFraction = (fullSize.height - topYPaddint - bottomYPadding) / CGFloat(maxValue - minValue)
  689. let yOffset = CGFloat(minValue) * stepYFraction
  690. let maxY = fullSize.height - CGFloat(minValue) * stepYFraction + yOffset - bottomYPadding
  691. let minY = fullSize.height - CGFloat(maxValue) * stepYFraction + yOffset - bottomYPadding
  692. return (minValue: minValue, minY: minY, maxValue: maxValue, maxY: maxY)
  693. }
  694. private func firstHourDate() -> Date {
  695. let firstDate = glucose.first?.dateString ?? Date()
  696. return firstDate.dateTruncated(from: .minute)!
  697. }
  698. private func firstHourPosition(viewWidth: CGFloat) -> CGFloat {
  699. let firstDate = glucose.first?.dateString ?? Date()
  700. let firstHour = firstHourDate()
  701. let lastDeltaTime = firstHour.timeIntervalSince(firstDate)
  702. let oneSecondWidth = oneSecondStep(viewWidth: viewWidth)
  703. return oneSecondWidth * CGFloat(lastDeltaTime)
  704. }
  705. }