MainChartView.swift 29 KB

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