MainChartView.swift 29 KB

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