MainChartView.swift 30 KB

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