MainChartView.swift 30 KB

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