MainChartView.swift 30 KB

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