MainChartView.swift 30 KB

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