MainChartView.swift 29 KB

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