MainChartView.swift 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759
  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.3
  30. }
  31. @Binding var glucose: [BloodGlucose]
  32. @Binding var suggestion: Suggestion?
  33. @Binding var tempBasals: [PumpHistoryEvent]
  34. @Binding var boluses: [PumpHistoryEvent]
  35. @Binding var hours: Int
  36. @Binding var maxBasal: Decimal
  37. @Binding var basalProfile: [BasalProfileEntry]
  38. @Binding var tempTargets: [TempTarget]
  39. @Binding var carbs: [CarbsEntry]
  40. 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. @State private var offset: CGFloat = 0
  53. private let calculationQueue = DispatchQueue(label: "MainChartView.calculationQueue")
  54. private var dateDormatter: DateFormatter {
  55. let formatter = DateFormatter()
  56. formatter.timeStyle = .short
  57. return formatter
  58. }
  59. private var glucoseFormatter: NumberFormatter {
  60. let formatter = NumberFormatter()
  61. formatter.numberStyle = .decimal
  62. formatter.maximumFractionDigits = 1
  63. return formatter
  64. }
  65. private var bolusFormatter: NumberFormatter {
  66. let formatter = NumberFormatter()
  67. formatter.numberStyle = .decimal
  68. formatter.minimumIntegerDigits = 0
  69. formatter.maximumFractionDigits = 2
  70. formatter.decimalSeparator = "."
  71. return formatter
  72. }
  73. private var carbsFormatter: NumberFormatter {
  74. let formatter = NumberFormatter()
  75. formatter.numberStyle = .decimal
  76. formatter.maximumFractionDigits = 0
  77. return formatter
  78. }
  79. // MARK: - Views
  80. var body: some View {
  81. GeometryReader { geo in
  82. ZStack(alignment: .leading) {
  83. yGridView(fullSize: geo.size)
  84. mainScrollView(fullSize: geo.size)
  85. glucoseLabelsView(fullSize: geo.size)
  86. }
  87. }
  88. }
  89. private func mainScrollView(fullSize: CGSize) -> some View {
  90. ScrollView(.horizontal, showsIndicators: false) {
  91. ScrollViewReader { scroll in
  92. ZStack(alignment: .top) {
  93. tempTargetsView(fullSize: fullSize).drawingGroup()
  94. basalView(fullSize: fullSize).drawingGroup()
  95. mainView(fullSize: fullSize).id(Config.endID)
  96. .drawingGroup()
  97. .onChange(of: glucose) { _ in
  98. scroll.scrollTo(Config.endID, anchor: .trailing)
  99. }
  100. .onChange(of: suggestion) { _ in
  101. scroll.scrollTo(Config.endID, anchor: .trailing)
  102. }
  103. .onChange(of: tempBasals) { _ in
  104. scroll.scrollTo(Config.endID, anchor: .trailing)
  105. }
  106. .onAppear {
  107. // add trigger to the end of main queue
  108. DispatchQueue.main.async {
  109. scroll.scrollTo(Config.endID, anchor: .trailing)
  110. didAppearTrigger = true
  111. }
  112. }
  113. }
  114. }
  115. }
  116. }
  117. private func yGridView(fullSize: CGSize) -> some View {
  118. Path { path in
  119. let range = glucoseYGange
  120. let step = (range.maxY - range.minY) / CGFloat(Config.yLinesCount)
  121. for line in 0 ... Config.yLinesCount {
  122. path.move(to: CGPoint(x: 0, y: range.minY + CGFloat(line) * step))
  123. path.addLine(to: CGPoint(x: fullSize.width, y: range.minY + CGFloat(line) * step))
  124. }
  125. }.stroke(Color.secondary, lineWidth: 0.2)
  126. }
  127. private func glucoseLabelsView(fullSize: CGSize) -> some View {
  128. ForEach(0 ..< Config.yLinesCount + 1) { line -> AnyView in
  129. let range = glucoseYGange
  130. let yStep = (range.maxY - range.minY) / CGFloat(Config.yLinesCount)
  131. let valueStep = Double(range.maxValue - range.minValue) / Double(Config.yLinesCount)
  132. let value = round(Double(range.maxValue) - Double(line) * valueStep) *
  133. (units == .mmolL ? Double(GlucoseUnits.exchangeRate) : 1)
  134. return Text(glucoseFormatter.string(from: value as NSNumber)!)
  135. .position(CGPoint(x: fullSize.width - 12, y: range.minY + CGFloat(line) * yStep))
  136. .font(.caption2)
  137. .asAny()
  138. }
  139. }
  140. private func basalView(fullSize: CGSize) -> some View {
  141. ZStack {
  142. tempBasalPath.fill(Color.tempBasal)
  143. tempBasalPath.stroke(Color.tempBasal, lineWidth: 1)
  144. regularBasalPath.stroke(Color.basal, lineWidth: 1)
  145. }
  146. .frame(width: fullGlucoseWidth(viewWidth: fullSize.width) + additionalWidth(viewWidth: fullSize.width))
  147. .frame(maxHeight: Config.basalHeight)
  148. .background(Color.secondary.opacity(0.1))
  149. .onChange(of: tempBasals) { _ in
  150. calculateBasalPoints(fullSize: fullSize)
  151. }
  152. .onChange(of: maxBasal) { _ in
  153. calculateBasalPoints(fullSize: fullSize)
  154. }
  155. .onChange(of: basalProfile) { _ in
  156. calculateBasalPoints(fullSize: fullSize)
  157. }
  158. .onChange(of: didAppearTrigger) { _ in
  159. calculateBasalPoints(fullSize: fullSize)
  160. }
  161. }
  162. private func mainView(fullSize: CGSize) -> some View {
  163. Group {
  164. VStack {
  165. ZStack {
  166. xGridView(fullSize: fullSize)
  167. carbsView(fullSize: fullSize)
  168. bolusView(fullSize: fullSize)
  169. glucoseView(fullSize: fullSize)
  170. predictionsView(fullSize: fullSize)
  171. }
  172. timeLabelsView(fullSize: fullSize)
  173. }
  174. }
  175. .frame(width: fullGlucoseWidth(viewWidth: fullSize.width) + additionalWidth(viewWidth: fullSize.width))
  176. }
  177. private func xGridView(fullSize: CGSize) -> some View {
  178. Path { path in
  179. for hour in 0 ..< hours + hours {
  180. let x = firstHourPosition(viewWidth: fullSize.width) +
  181. oneSecondStep(viewWidth: fullSize.width) *
  182. CGFloat(hour) * CGFloat(1.hours.timeInterval)
  183. path.move(to: CGPoint(x: x, y: 0))
  184. path.addLine(to: CGPoint(x: x, y: fullSize.height - 20))
  185. }
  186. }
  187. .stroke(Color.secondary, lineWidth: 0.2)
  188. }
  189. private func timeLabelsView(fullSize: CGSize) -> some View {
  190. ZStack {
  191. // X time labels
  192. ForEach(0 ..< hours + hours) { hour in
  193. Text(dateDormatter.string(from: firstHourDate().addingTimeInterval(hour.hours.timeInterval)))
  194. .font(.caption)
  195. .position(
  196. x: firstHourPosition(viewWidth: fullSize.width) +
  197. oneSecondStep(viewWidth: fullSize.width) *
  198. CGFloat(hour) * CGFloat(1.hours.timeInterval),
  199. y: 10.0
  200. )
  201. .foregroundColor(.secondary)
  202. }
  203. }.frame(maxHeight: 20)
  204. }
  205. private func glucoseView(fullSize: CGSize) -> some View {
  206. Path { path in
  207. for rect in glucoseDots {
  208. path.addEllipse(in: rect)
  209. }
  210. }
  211. .fill(Color.loopGreen)
  212. .onChange(of: glucose) { _ in
  213. update(fullSize: fullSize)
  214. }
  215. .onChange(of: didAppearTrigger) { _ in
  216. update(fullSize: fullSize)
  217. }
  218. .onReceive(Foundation.NotificationCenter.default.publisher(for: UIApplication.willEnterForegroundNotification)) { _ in
  219. update(fullSize: fullSize)
  220. }
  221. }
  222. private func bolusView(fullSize: CGSize) -> some View {
  223. ZStack {
  224. bolusPath
  225. .fill(Color.insulin)
  226. bolusPath
  227. .stroke(Color.primary, lineWidth: 0.5)
  228. ForEach(bolusDots, id: \.rect.minX) { info -> AnyView in
  229. let position = CGPoint(x: info.rect.midX, y: info.rect.maxY + 8)
  230. return Text(bolusFormatter.string(from: info.value as NSNumber)!).font(.caption2)
  231. .position(position)
  232. .asAny()
  233. }
  234. }
  235. .onChange(of: boluses) { _ in
  236. calculateBolusDots(fullSize: fullSize)
  237. }
  238. .onChange(of: didAppearTrigger) { _ in
  239. calculateBolusDots(fullSize: fullSize)
  240. }
  241. }
  242. private func carbsView(fullSize: CGSize) -> some View {
  243. ZStack {
  244. carbsPath
  245. .fill(Color.loopYellow)
  246. carbsPath
  247. .stroke(Color.primary, lineWidth: 0.5)
  248. ForEach(carbsDots, id: \.rect.minX) { info -> AnyView in
  249. let position = CGPoint(x: info.rect.midX, y: info.rect.minY - 8)
  250. return Text(carbsFormatter.string(from: info.value as NSNumber)!).font(.caption2)
  251. .position(position)
  252. .asAny()
  253. }
  254. }
  255. .onChange(of: carbs) { _ in
  256. calculateCarbsDots(fullSize: fullSize)
  257. }
  258. .onChange(of: didAppearTrigger) { _ in
  259. calculateCarbsDots(fullSize: fullSize)
  260. }
  261. }
  262. private func tempTargetsView(fullSize: CGSize) -> some View {
  263. ZStack {
  264. tempTargetsPath
  265. .fill(Color.tempBasal.opacity(0.5))
  266. }
  267. .onChange(of: glucose) { _ in
  268. calculateTempTargetsRects(fullSize: fullSize)
  269. }
  270. .onChange(of: tempTargets) { _ in
  271. calculateTempTargetsRects(fullSize: fullSize)
  272. }
  273. .onChange(of: didAppearTrigger) { _ in
  274. calculateTempTargetsRects(fullSize: fullSize)
  275. }
  276. }
  277. private func predictionsView(fullSize: CGSize) -> some View {
  278. Group {
  279. Path { path in
  280. for rect in predictionDots[.iob] ?? [] {
  281. path.addEllipse(in: rect)
  282. }
  283. }.fill(Color.insulin)
  284. Path { path in
  285. for rect in predictionDots[.cob] ?? [] {
  286. path.addEllipse(in: rect)
  287. }
  288. }.fill(Color.loopYellow)
  289. Path { path in
  290. for rect in predictionDots[.zt] ?? [] {
  291. path.addEllipse(in: rect)
  292. }
  293. }.fill(Color.zt)
  294. Path { path in
  295. for rect in predictionDots[.uam] ?? [] {
  296. path.addEllipse(in: rect)
  297. }
  298. }.fill(Color.uam)
  299. }
  300. .onChange(of: suggestion) { _ in
  301. update(fullSize: fullSize)
  302. }
  303. }
  304. }
  305. // MARK: - Calculations
  306. extension MainChartView {
  307. private func update(fullSize: CGSize) {
  308. calculatePredictionDots(fullSize: fullSize, type: .iob)
  309. calculatePredictionDots(fullSize: fullSize, type: .cob)
  310. calculatePredictionDots(fullSize: fullSize, type: .zt)
  311. calculatePredictionDots(fullSize: fullSize, type: .uam)
  312. calculateGlucoseDots(fullSize: fullSize)
  313. calculateBolusDots(fullSize: fullSize)
  314. calculateCarbsDots(fullSize: fullSize)
  315. calculateTempTargetsRects(fullSize: fullSize)
  316. calculateTempTargetsRects(fullSize: fullSize)
  317. }
  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. }