MainChartView.swift 48 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246
  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. struct AnnouncementDot {
  15. let rect: CGRect
  16. let value: Decimal
  17. let note: String
  18. }
  19. typealias GlucoseYRange = (minValue: Int, minY: CGFloat, maxValue: Int, maxY: CGFloat)
  20. struct MainChartView: View {
  21. private enum Config {
  22. static let endID = "End"
  23. static let basalHeight: CGFloat = 80
  24. static let topYPadding: CGFloat = 20
  25. static let bottomYPadding: CGFloat = 80
  26. static let minAdditionalWidth: CGFloat = 150
  27. static let maxGlucose = 270
  28. static let minGlucose = 45
  29. static let yLinesCount = 5
  30. static let glucoseScale: CGFloat = 2 // default 2
  31. static let bolusSize: CGFloat = 8
  32. static let bolusScale: CGFloat = 2.5
  33. static let carbsSize: CGFloat = 10
  34. static let fpuSize: CGFloat = 5
  35. static let carbsScale: CGFloat = 0.3
  36. static let fpuScale: CGFloat = 1
  37. static let announcementSize: CGFloat = 8
  38. static let announcementScale: CGFloat = 2.5
  39. static let owlSeize: CGFloat = 25
  40. static let owlOffset: CGFloat = 80
  41. }
  42. private enum Command {
  43. static let open = "🔴"
  44. static let closed = "🟢"
  45. static let suspend = "❌"
  46. static let resume = "✅"
  47. static let tempbasal = "basal"
  48. static let bolus = "💧"
  49. }
  50. @Binding var glucose: [BloodGlucose]
  51. @Binding var isManual: [BloodGlucose]
  52. @Binding var suggestion: Suggestion?
  53. @Binding var tempBasals: [PumpHistoryEvent]
  54. @Binding var boluses: [PumpHistoryEvent]
  55. @Binding var suspensions: [PumpHistoryEvent]
  56. @Binding var announcement: [Announcement]
  57. @Binding var hours: Int
  58. @Binding var maxBasal: Decimal
  59. @Binding var autotunedBasalProfile: [BasalProfileEntry]
  60. @Binding var basalProfile: [BasalProfileEntry]
  61. @Binding var tempTargets: [TempTarget]
  62. @Binding var carbs: [CarbsEntry]
  63. @Binding var timerDate: Date
  64. @Binding var units: GlucoseUnits
  65. @Binding var smooth: Bool
  66. @Binding var highGlucose: Decimal
  67. @Binding var lowGlucose: Decimal
  68. @Binding var screenHours: Int16
  69. @Binding var displayXgridLines: Bool
  70. @Binding var displayYgridLines: Bool
  71. @Binding var thresholdLines: Bool
  72. @State var didAppearTrigger = false
  73. @State private var glucoseDots: [CGRect] = []
  74. @State private var manualGlucoseDots: [CGRect] = []
  75. @State private var announcementDots: [AnnouncementDot] = []
  76. @State private var announcementPath = Path()
  77. @State private var manualGlucoseDotsCenter: [CGRect] = []
  78. @State private var unSmoothedGlucoseDots: [CGRect] = []
  79. @State private var predictionDots: [PredictionType: [CGRect]] = [:]
  80. @State private var bolusDots: [DotInfo] = []
  81. @State private var bolusPath = Path()
  82. @State private var tempBasalPath = Path()
  83. @State private var regularBasalPath = Path()
  84. @State private var tempTargetsPath = Path()
  85. @State private var suspensionsPath = Path()
  86. @State private var carbsDots: [DotInfo] = []
  87. @State private var carbsPath = Path()
  88. @State private var fpuDots: [DotInfo] = []
  89. @State private var fpuPath = Path()
  90. @State private var glucoseYRange: GlucoseYRange = (0, 0, 0, 0)
  91. @State private var offset: CGFloat = 0
  92. @State private var cachedMaxBasalRate: Decimal?
  93. private let calculationQueue = DispatchQueue(label: "MainChartView.calculationQueue")
  94. private var dateFormatter: DateFormatter {
  95. let formatter = DateFormatter()
  96. formatter.timeStyle = .short
  97. return formatter
  98. }
  99. private var date24Formatter: DateFormatter {
  100. let formatter = DateFormatter()
  101. formatter.locale = Locale(identifier: "en_US_POSIX")
  102. formatter.setLocalizedDateFormatFromTemplate("HH")
  103. return formatter
  104. }
  105. private var glucoseFormatter: NumberFormatter {
  106. let formatter = NumberFormatter()
  107. formatter.numberStyle = .decimal
  108. formatter.maximumFractionDigits = 1
  109. return formatter
  110. }
  111. private var bolusFormatter: NumberFormatter {
  112. let formatter = NumberFormatter()
  113. formatter.numberStyle = .decimal
  114. formatter.minimumIntegerDigits = 0
  115. formatter.maximumFractionDigits = 2
  116. formatter.decimalSeparator = "."
  117. return formatter
  118. }
  119. private var carbsFormatter: NumberFormatter {
  120. let formatter = NumberFormatter()
  121. formatter.numberStyle = .decimal
  122. formatter.maximumFractionDigits = 0
  123. return formatter
  124. }
  125. private var fpuFormatter: NumberFormatter {
  126. let formatter = NumberFormatter()
  127. formatter.numberStyle = .decimal
  128. formatter.maximumFractionDigits = 1
  129. formatter.decimalSeparator = "."
  130. formatter.minimumIntegerDigits = 0
  131. return formatter
  132. }
  133. @Environment(\.horizontalSizeClass) var hSizeClass
  134. @Environment(\.verticalSizeClass) var vSizeClass
  135. // MARK: - Views
  136. var body: some View {
  137. GeometryReader { geo in
  138. ZStack(alignment: .leading) {
  139. yGridView(fullSize: geo.size)
  140. mainScrollView(fullSize: geo.size)
  141. glucoseLabelsView(fullSize: geo.size)
  142. }
  143. .onChange(of: hSizeClass) { _ in
  144. update(fullSize: geo.size)
  145. }
  146. .onChange(of: vSizeClass) { _ in
  147. update(fullSize: geo.size)
  148. }
  149. .onChange(of: screenHours) { _ in
  150. update(fullSize: geo.size)
  151. // scroll.scrollTo(Config.endID, anchor: .trailing)
  152. }
  153. .onReceive(
  154. Foundation.NotificationCenter.default
  155. .publisher(for: UIDevice.orientationDidChangeNotification)
  156. ) { _ in
  157. update(fullSize: geo.size)
  158. }
  159. }
  160. }
  161. private func mainScrollView(fullSize: CGSize) -> some View {
  162. ScrollView(.horizontal, showsIndicators: false) {
  163. ScrollViewReader { scroll in
  164. ZStack(alignment: .top) {
  165. tempTargetsView(fullSize: fullSize).drawingGroup()
  166. ZStack {
  167. basalView(fullSize: fullSize).drawingGroup()
  168. Text(calculateTINS())
  169. .font(.callout).fontWeight(.bold)
  170. }
  171. mainView(fullSize: fullSize).id(Config.endID)
  172. .drawingGroup()
  173. .onChange(of: glucose) { _ in
  174. scroll.scrollTo(Config.endID, anchor: .trailing)
  175. }
  176. .onChange(of: suggestion) { _ in
  177. scroll.scrollTo(Config.endID, anchor: .trailing)
  178. }
  179. .onChange(of: tempBasals) { _ in
  180. scroll.scrollTo(Config.endID, anchor: .trailing)
  181. }
  182. .onChange(of: screenHours) { _ in
  183. scroll.scrollTo(Config.endID, anchor: .trailing)
  184. }
  185. .onAppear {
  186. // add trigger to the end of main queue
  187. DispatchQueue.main.async {
  188. scroll.scrollTo(Config.endID, anchor: .trailing)
  189. didAppearTrigger = true
  190. }
  191. }
  192. }
  193. }
  194. }
  195. }
  196. private func yGridView(fullSize: CGSize) -> some View {
  197. let useColour = displayYgridLines ? Color.secondary : Color.clear
  198. return ZStack {
  199. Path { path in
  200. let range = glucoseYRange
  201. let step = (range.maxY - range.minY) / CGFloat(Config.yLinesCount)
  202. for line in 0 ... Config.yLinesCount {
  203. path.move(to: CGPoint(x: 0, y: range.minY + CGFloat(line) * step))
  204. path.addLine(to: CGPoint(x: fullSize.width, y: range.minY + CGFloat(line) * step))
  205. }
  206. }.stroke(useColour, lineWidth: 0.15)
  207. // horizontal limits
  208. if thresholdLines {
  209. let range = glucoseYRange
  210. let topstep = (range.maxY - range.minY) / CGFloat(range.maxValue - range.minValue) *
  211. (CGFloat(range.maxValue) - CGFloat(highGlucose))
  212. if CGFloat(range.maxValue) > CGFloat(highGlucose) {
  213. Path { path in
  214. path.move(to: CGPoint(x: 0, y: range.minY + topstep))
  215. path.addLine(to: CGPoint(x: fullSize.width, y: range.minY + topstep))
  216. }.stroke(Color.loopYellow, lineWidth: 0.5) // .StrokeStyle(lineWidth: 0.5, dash: [5])
  217. }
  218. let yrange = glucoseYRange
  219. let bottomstep = (yrange.maxY - yrange.minY) / CGFloat(yrange.maxValue - yrange.minValue) *
  220. (CGFloat(yrange.maxValue) - CGFloat(lowGlucose))
  221. if CGFloat(yrange.minValue) < CGFloat(lowGlucose) {
  222. Path { path in
  223. path.move(to: CGPoint(x: 0, y: yrange.minY + bottomstep))
  224. path.addLine(to: CGPoint(x: fullSize.width, y: yrange.minY + bottomstep))
  225. }.stroke(Color.loopRed, lineWidth: 0.5)
  226. }
  227. }
  228. }
  229. }
  230. private func glucoseLabelsView(fullSize: CGSize) -> some View {
  231. ForEach(0 ..< Config.yLinesCount + 1, id: \.self) { line -> AnyView in
  232. let range = glucoseYRange
  233. let yStep = (range.maxY - range.minY) / CGFloat(Config.yLinesCount)
  234. let valueStep = Double(range.maxValue - range.minValue) / Double(Config.yLinesCount)
  235. let value = round(Double(range.maxValue) - Double(line) * valueStep) *
  236. (units == .mmolL ? Double(GlucoseUnits.exchangeRate) : 1)
  237. return Text(glucoseFormatter.string(from: value as NSNumber)!)
  238. .position(CGPoint(x: fullSize.width - 12, y: range.minY + CGFloat(line) * yStep))
  239. .font(.caption2)
  240. .asAny()
  241. }
  242. }
  243. private func basalView(fullSize: CGSize) -> some View {
  244. ZStack {
  245. tempBasalPath.fill(Color.basal.opacity(0.5))
  246. tempBasalPath.stroke(Color.insulin, lineWidth: 1)
  247. regularBasalPath.stroke(Color.insulin, style: StrokeStyle(lineWidth: 0.7, dash: [4]))
  248. suspensionsPath.stroke(Color.loopGray.opacity(0.7), style: StrokeStyle(lineWidth: 0.7)).scaleEffect(x: 1, y: -1)
  249. suspensionsPath.fill(Color.loopGray.opacity(0.2)).scaleEffect(x: 1, y: -1)
  250. }
  251. .scaleEffect(x: 1, y: -1)
  252. .frame(width: fullGlucoseWidth(viewWidth: fullSize.width) + additionalWidth(viewWidth: fullSize.width))
  253. .frame(maxHeight: Config.basalHeight)
  254. .background(colorScheme == .dark ? Color.black.opacity(0.8) : Color.clear)
  255. .onChange(of: tempBasals) { _ in
  256. calculateBasalPoints(fullSize: fullSize)
  257. }
  258. .onChange(of: suspensions) { _ in
  259. calculateSuspensions(fullSize: fullSize)
  260. }
  261. .onChange(of: maxBasal) { _ in
  262. calculateBasalPoints(fullSize: fullSize)
  263. }
  264. .onChange(of: autotunedBasalProfile) { _ in
  265. calculateBasalPoints(fullSize: fullSize)
  266. }
  267. .onChange(of: didAppearTrigger) { _ in
  268. calculateBasalPoints(fullSize: fullSize)
  269. }
  270. }
  271. private func mainView(fullSize: CGSize) -> some View {
  272. Group {
  273. VStack {
  274. ZStack {
  275. xGridView(fullSize: fullSize)
  276. carbsView(fullSize: fullSize)
  277. fpuView(fullSize: fullSize)
  278. bolusView(fullSize: fullSize)
  279. if smooth { unSmoothedGlucoseView(fullSize: fullSize) }
  280. glucoseView(fullSize: fullSize)
  281. manualGlucoseView(fullSize: fullSize)
  282. manualGlucoseCenterView(fullSize: fullSize)
  283. announcementView(fullSize: fullSize)
  284. predictionsView(fullSize: fullSize)
  285. }
  286. timeLabelsView(fullSize: fullSize)
  287. }
  288. }
  289. .frame(width: fullGlucoseWidth(viewWidth: fullSize.width) + additionalWidth(viewWidth: fullSize.width))
  290. }
  291. @Environment(\.colorScheme) var colorScheme
  292. private func xGridView(fullSize: CGSize) -> some View {
  293. let useColour = displayXgridLines ? Color.secondary : Color.clear
  294. return ZStack {
  295. Path { path in
  296. for hour in 0 ..< hours + hours {
  297. let x = firstHourPosition(viewWidth: fullSize.width) +
  298. oneSecondStep(viewWidth: fullSize.width) *
  299. CGFloat(hour) * CGFloat(1.hours.timeInterval)
  300. path.move(to: CGPoint(x: x, y: 0))
  301. path.addLine(to: CGPoint(x: x, y: fullSize.height - 20))
  302. }
  303. }
  304. .stroke(useColour, lineWidth: 0.15)
  305. Path { path in // vertical timeline
  306. let x = timeToXCoordinate(timerDate.timeIntervalSince1970, fullSize: fullSize)
  307. path.move(to: CGPoint(x: x, y: 0))
  308. path.addLine(to: CGPoint(x: x, y: fullSize.height - 20))
  309. }
  310. .stroke(
  311. colorScheme == .dark ? Color.white : Color.black,
  312. style: StrokeStyle(lineWidth: 0.5, dash: [5])
  313. )
  314. }
  315. }
  316. private func timeLabelsView(fullSize: CGSize) -> some View {
  317. let format = screenHours > 6 ? date24Formatter : dateFormatter
  318. return ZStack {
  319. // X time labels
  320. ForEach(0 ..< hours + hours) { hour in
  321. Text(format.string(from: firstHourDate().addingTimeInterval(hour.hours.timeInterval)))
  322. .font(.caption)
  323. .position(
  324. x: firstHourPosition(viewWidth: fullSize.width) +
  325. oneSecondStep(viewWidth: fullSize.width) *
  326. CGFloat(hour) * CGFloat(1.hours.timeInterval),
  327. y: 10.0
  328. )
  329. .foregroundColor(.secondary)
  330. }
  331. }.frame(maxHeight: 20)
  332. }
  333. private func glucoseView(fullSize: CGSize) -> some View {
  334. Path { path in
  335. for rect in glucoseDots {
  336. path.addEllipse(in: rect)
  337. }
  338. }
  339. .fill(Color.loopGreen)
  340. .onChange(of: glucose) { _ in
  341. update(fullSize: fullSize)
  342. }
  343. .onChange(of: didAppearTrigger) { _ in
  344. update(fullSize: fullSize)
  345. }
  346. .onReceive(Foundation.NotificationCenter.default.publisher(for: UIApplication.willEnterForegroundNotification)) { _ in
  347. update(fullSize: fullSize)
  348. }
  349. }
  350. private func manualGlucoseView(fullSize: CGSize) -> some View {
  351. Path { path in
  352. for rect in manualGlucoseDots {
  353. path.addEllipse(in: rect)
  354. }
  355. }
  356. .fill(Color.gray)
  357. .onChange(of: isManual) { _ in
  358. update(fullSize: fullSize)
  359. }
  360. .onChange(of: didAppearTrigger) { _ in
  361. update(fullSize: fullSize)
  362. }
  363. .onReceive(Foundation.NotificationCenter.default.publisher(for: UIApplication.willEnterForegroundNotification)) { _ in
  364. update(fullSize: fullSize)
  365. }
  366. }
  367. private func announcementView(fullSize: CGSize) -> some View {
  368. ZStack {
  369. ForEach(announcementDots, id: \.rect.minX) { info -> AnyView in
  370. let position = CGPoint(x: info.rect.midX + 5, y: info.rect.maxY - Config.owlOffset)
  371. let type: String =
  372. info.note.contains("true") ?
  373. Command.open :
  374. info.note.contains("false") ?
  375. Command.closed :
  376. info.note.contains("suspend") ?
  377. Command.suspend :
  378. info.note.contains("resume") ?
  379. Command.resume :
  380. info.note.contains("tempbasal") ?
  381. Command.tempbasal : Command.bolus
  382. VStack {
  383. Text(type).font(.caption2).foregroundStyle(.orange)
  384. Image("owl").resizable().frame(maxWidth: Config.owlSeize, maxHeight: Config.owlSeize).scaledToFill()
  385. }.position(position).asAny()
  386. }
  387. }
  388. .onChange(of: announcement) { _ in
  389. calculateAnnouncementDots(fullSize: fullSize)
  390. }
  391. .onChange(of: didAppearTrigger) { _ in
  392. calculateAnnouncementDots(fullSize: fullSize)
  393. }
  394. }
  395. private func manualGlucoseCenterView(fullSize: CGSize) -> some View {
  396. Path { path in
  397. for rect in manualGlucoseDotsCenter {
  398. path.addEllipse(in: rect)
  399. }
  400. }
  401. .fill(Color.red)
  402. .onChange(of: isManual) { _ in
  403. update(fullSize: fullSize)
  404. }
  405. .onChange(of: didAppearTrigger) { _ in
  406. update(fullSize: fullSize)
  407. }
  408. .onReceive(
  409. Foundation.NotificationCenter.default
  410. .publisher(for: UIApplication.willEnterForegroundNotification)
  411. ) { _ in
  412. update(fullSize: fullSize)
  413. }
  414. }
  415. private func unSmoothedGlucoseView(fullSize: CGSize) -> some View {
  416. Path { path in
  417. var lines: [CGPoint] = []
  418. for rect in unSmoothedGlucoseDots {
  419. lines.append(CGPoint(x: rect.midX, y: rect.midY))
  420. path.addEllipse(in: rect)
  421. }
  422. path.addLines(lines)
  423. }
  424. .stroke(Color.loopGray, lineWidth: 0.5)
  425. .onChange(of: glucose) { _ in
  426. update(fullSize: fullSize)
  427. }
  428. .onChange(of: didAppearTrigger) { _ in
  429. update(fullSize: fullSize)
  430. }
  431. .onReceive(Foundation.NotificationCenter.default.publisher(for: UIApplication.willEnterForegroundNotification)) { _ in
  432. update(fullSize: fullSize)
  433. }
  434. }
  435. private func bolusView(fullSize: CGSize) -> some View {
  436. ZStack {
  437. bolusPath
  438. .fill(Color.insulin)
  439. bolusPath
  440. .stroke(Color.primary, lineWidth: 0.5)
  441. ForEach(bolusDots, id: \.rect.minX) { info -> AnyView in
  442. let position = CGPoint(x: info.rect.midX, y: info.rect.maxY + 8)
  443. return Text(bolusFormatter.string(from: info.value as NSNumber)!).font(.caption2)
  444. .position(position)
  445. .asAny()
  446. }
  447. }
  448. .onChange(of: boluses) { _ in
  449. calculateBolusDots(fullSize: fullSize)
  450. }
  451. .onChange(of: didAppearTrigger) { _ in
  452. calculateBolusDots(fullSize: fullSize)
  453. }
  454. }
  455. private func carbsView(fullSize: CGSize) -> some View {
  456. ZStack {
  457. carbsPath
  458. .fill(Color.loopYellow)
  459. carbsPath
  460. .stroke(Color.primary, lineWidth: 0.5)
  461. ForEach(carbsDots, id: \.rect.minX) { info -> AnyView in
  462. let position = CGPoint(x: info.rect.midX, y: info.rect.minY - 8)
  463. return Text(carbsFormatter.string(from: info.value as NSNumber)!).font(.caption2)
  464. .position(position)
  465. .asAny()
  466. }
  467. }
  468. .onChange(of: carbs) { _ in
  469. calculateCarbsDots(fullSize: fullSize)
  470. }
  471. .onChange(of: didAppearTrigger) { _ in
  472. calculateCarbsDots(fullSize: fullSize)
  473. }
  474. }
  475. private func fpuView(fullSize: CGSize) -> some View {
  476. ZStack {
  477. fpuPath
  478. .fill(.orange.opacity(0.5))
  479. fpuPath
  480. .stroke(Color.primary, lineWidth: 0.2)
  481. }
  482. .onChange(of: carbs) { _ in
  483. calculateFPUsDots(fullSize: fullSize)
  484. }
  485. .onChange(of: didAppearTrigger) { _ in
  486. calculateFPUsDots(fullSize: fullSize)
  487. }
  488. }
  489. private func tempTargetsView(fullSize: CGSize) -> some View {
  490. ZStack {
  491. tempTargetsPath
  492. .fill(Color.tempBasal.opacity(0.5))
  493. tempTargetsPath
  494. .stroke(Color.basal.opacity(0.5), lineWidth: 1)
  495. }
  496. .onChange(of: glucose) { _ in
  497. calculateTempTargetsRects(fullSize: fullSize)
  498. }
  499. .onChange(of: tempTargets) { _ in
  500. calculateTempTargetsRects(fullSize: fullSize)
  501. }
  502. .onChange(of: didAppearTrigger) { _ in
  503. calculateTempTargetsRects(fullSize: fullSize)
  504. }
  505. }
  506. private func predictionsView(fullSize: CGSize) -> some View {
  507. Group {
  508. Path { path in
  509. for rect in predictionDots[.iob] ?? [] {
  510. path.addEllipse(in: rect)
  511. }
  512. }.fill(Color.insulin)
  513. Path { path in
  514. for rect in predictionDots[.cob] ?? [] {
  515. path.addEllipse(in: rect)
  516. }
  517. }.fill(Color.loopYellow)
  518. Path { path in
  519. for rect in predictionDots[.zt] ?? [] {
  520. path.addEllipse(in: rect)
  521. }
  522. }.fill(Color.zt)
  523. Path { path in
  524. for rect in predictionDots[.uam] ?? [] {
  525. path.addEllipse(in: rect)
  526. }
  527. }.fill(Color.uam)
  528. }
  529. .onChange(of: suggestion) { _ in
  530. update(fullSize: fullSize)
  531. }
  532. }
  533. }
  534. // MARK: - Calculations
  535. extension MainChartView {
  536. private func update(fullSize: CGSize) {
  537. calculatePredictionDots(fullSize: fullSize, type: .iob)
  538. calculatePredictionDots(fullSize: fullSize, type: .cob)
  539. calculatePredictionDots(fullSize: fullSize, type: .zt)
  540. calculatePredictionDots(fullSize: fullSize, type: .uam)
  541. calculateGlucoseDots(fullSize: fullSize)
  542. calculateManualGlucoseDots(fullSize: fullSize)
  543. calculateManualGlucoseDotsCenter(fullSize: fullSize)
  544. calculateAnnouncementDots(fullSize: fullSize)
  545. calculateUnSmoothedGlucoseDots(fullSize: fullSize)
  546. calculateBolusDots(fullSize: fullSize)
  547. calculateCarbsDots(fullSize: fullSize)
  548. calculateFPUsDots(fullSize: fullSize)
  549. calculateTempTargetsRects(fullSize: fullSize)
  550. calculateBasalPoints(fullSize: fullSize)
  551. calculateSuspensions(fullSize: fullSize)
  552. }
  553. private func calculateGlucoseDots(fullSize: CGSize) {
  554. calculationQueue.async {
  555. let dots = glucose.concurrentMap { value -> CGRect in
  556. let position = glucoseToCoordinate(value, fullSize: fullSize)
  557. return CGRect(x: position.x - 2, y: position.y - 2, width: 4, height: 4)
  558. }
  559. let range = self.getGlucoseYRange(fullSize: fullSize)
  560. DispatchQueue.main.async {
  561. glucoseYRange = range
  562. glucoseDots = dots
  563. }
  564. }
  565. }
  566. private func calculateManualGlucoseDots(fullSize: CGSize) {
  567. calculationQueue.async {
  568. let dots = isManual.concurrentMap { value -> CGRect in
  569. let position = glucoseToCoordinate(value, fullSize: fullSize)
  570. return CGRect(x: position.x - 2, y: position.y - 2, width: 14, height: 14)
  571. }
  572. let range = self.getGlucoseYRange(fullSize: fullSize)
  573. DispatchQueue.main.async {
  574. glucoseYRange = range
  575. manualGlucoseDots = dots
  576. }
  577. }
  578. }
  579. private func calculateManualGlucoseDotsCenter(fullSize: CGSize) {
  580. calculationQueue.async {
  581. let dots = isManual.concurrentMap { value -> CGRect in
  582. let position = glucoseToCoordinate(value, fullSize: fullSize)
  583. return CGRect(x: position.x, y: position.y, width: 10, height: 10)
  584. }
  585. let range = self.getGlucoseYRange(fullSize: fullSize)
  586. DispatchQueue.main.async {
  587. glucoseYRange = range
  588. manualGlucoseDotsCenter = dots
  589. }
  590. }
  591. }
  592. private func calculateAnnouncementDots(fullSize: CGSize) {
  593. calculationQueue.async {
  594. let dots = announcement.map { value -> AnnouncementDot in
  595. let center = timeToInterpolatedPoint(value.createdAt.timeIntervalSince1970, fullSize: fullSize)
  596. let size = Config.announcementSize * Config.announcementScale
  597. let rect = CGRect(x: center.x - size / 2, y: center.y - size / 2, width: size, height: size)
  598. let note = value.notes
  599. return AnnouncementDot(rect: rect, value: 10, note: note)
  600. }
  601. let path = Path { path in
  602. for dot in dots {
  603. path.addEllipse(in: dot.rect)
  604. }
  605. }
  606. let range = self.getGlucoseYRange(fullSize: fullSize)
  607. DispatchQueue.main.async {
  608. glucoseYRange = range
  609. announcementDots = dots
  610. announcementPath = path
  611. }
  612. }
  613. }
  614. private func calculateUnSmoothedGlucoseDots(fullSize: CGSize) {
  615. calculationQueue.async {
  616. let dots = glucose.concurrentMap { value -> CGRect in
  617. let position = UnSmoothedGlucoseToCoordinate(value, fullSize: fullSize)
  618. return CGRect(x: position.x - 2, y: position.y - 2, width: 4, height: 4)
  619. }
  620. let range = self.getGlucoseYRange(fullSize: fullSize)
  621. DispatchQueue.main.async {
  622. glucoseYRange = range
  623. unSmoothedGlucoseDots = dots
  624. }
  625. }
  626. }
  627. private func calculateBolusDots(fullSize: CGSize) {
  628. calculationQueue.async {
  629. let dots = boluses.map { value -> DotInfo in
  630. let center = timeToInterpolatedPoint(value.timestamp.timeIntervalSince1970, fullSize: fullSize)
  631. let size = Config.bolusSize + CGFloat(value.amount ?? 0) * Config.bolusScale
  632. let rect = CGRect(x: center.x - size / 2, y: center.y - size / 2, width: size, height: size)
  633. return DotInfo(rect: rect, value: value.amount ?? 0)
  634. }
  635. let path = Path { path in
  636. for dot in dots {
  637. path.addEllipse(in: dot.rect)
  638. }
  639. }
  640. DispatchQueue.main.async {
  641. bolusDots = dots
  642. bolusPath = path
  643. }
  644. }
  645. }
  646. private func calculateCarbsDots(fullSize: CGSize) {
  647. calculationQueue.async {
  648. let realCarbs = carbs.filter { !($0.isFPU ?? false) }
  649. let dots = realCarbs.map { value -> DotInfo in
  650. let center = timeToInterpolatedPoint(value.createdAt.timeIntervalSince1970, fullSize: fullSize)
  651. let size = Config.carbsSize + CGFloat(value.carbs) * Config.carbsScale
  652. let rect = CGRect(x: center.x - size / 2, y: center.y - size / 2, width: size, height: size)
  653. return DotInfo(rect: rect, value: value.carbs)
  654. }
  655. let path = Path { path in
  656. for dot in dots {
  657. path.addEllipse(in: dot.rect)
  658. }
  659. }
  660. DispatchQueue.main.async {
  661. carbsDots = dots
  662. carbsPath = path
  663. }
  664. }
  665. }
  666. private func calculateFPUsDots(fullSize: CGSize) {
  667. calculationQueue.async {
  668. let fpus = carbs.filter { $0.isFPU ?? false }
  669. let dots = fpus.map { value -> DotInfo in
  670. let center = timeToInterpolatedPoint(value.createdAt.timeIntervalSince1970, fullSize: fullSize)
  671. let size = Config.fpuSize + CGFloat(value.carbs) * Config.fpuScale
  672. let rect = CGRect(x: center.x - size / 2, y: center.y - size / 2, width: size, height: size)
  673. return DotInfo(rect: rect, value: value.carbs)
  674. }
  675. let path = Path { path in
  676. for dot in dots {
  677. path.addEllipse(in: dot.rect)
  678. }
  679. }
  680. DispatchQueue.main.async {
  681. fpuDots = dots
  682. fpuPath = path
  683. }
  684. }
  685. }
  686. private func calculatePredictionDots(fullSize: CGSize, type: PredictionType) {
  687. calculationQueue.async {
  688. let values: [Int] = { () -> [Int] in
  689. switch type {
  690. case .iob:
  691. return suggestion?.predictions?.iob ?? []
  692. case .cob:
  693. return suggestion?.predictions?.cob ?? []
  694. case .zt:
  695. return suggestion?.predictions?.zt ?? []
  696. case .uam:
  697. return suggestion?.predictions?.uam ?? []
  698. }
  699. }()
  700. var index = 0
  701. let dots = values.map { value -> CGRect in
  702. let position = predictionToCoordinate(value, fullSize: fullSize, index: index)
  703. index += 1
  704. return CGRect(x: position.x - 2, y: position.y - 2, width: 4, height: 4)
  705. }
  706. DispatchQueue.main.async {
  707. predictionDots[type] = dots
  708. }
  709. }
  710. }
  711. private func calculateBasalPoints(fullSize: CGSize) {
  712. calculationQueue.async {
  713. self.cachedMaxBasalRate = nil
  714. let dayAgoTime = Date().addingTimeInterval(-1.days.timeInterval).timeIntervalSince1970
  715. let firstTempTime = (tempBasals.first?.timestamp ?? Date()).timeIntervalSince1970
  716. var lastTimeEnd = firstTempTime
  717. let firstRegularBasalPoints = findRegularBasalPoints(
  718. timeBegin: dayAgoTime,
  719. timeEnd: firstTempTime,
  720. fullSize: fullSize,
  721. autotuned: false
  722. )
  723. let tempBasalPoints = firstRegularBasalPoints + tempBasals.chunks(ofCount: 2).map { chunk -> [CGPoint] in
  724. let chunk = Array(chunk)
  725. guard chunk.count == 2, chunk[0].type == .tempBasal, chunk[1].type == .tempBasalDuration else { return [] }
  726. let timeBegin = chunk[0].timestamp.timeIntervalSince1970
  727. let timeEnd = timeBegin + (chunk[1].durationMin ?? 0).minutes.timeInterval
  728. let rateCost = Config.basalHeight / CGFloat(maxBasalRate())
  729. let x0 = timeToXCoordinate(timeBegin, fullSize: fullSize)
  730. let y0 = Config.basalHeight - CGFloat(chunk[0].rate ?? 0) * rateCost
  731. let regularPoints = findRegularBasalPoints(
  732. timeBegin: lastTimeEnd,
  733. timeEnd: timeBegin,
  734. fullSize: fullSize,
  735. autotuned: false
  736. )
  737. lastTimeEnd = timeEnd
  738. return regularPoints + [CGPoint(x: x0, y: y0)]
  739. }.flatMap { $0 }
  740. let tempBasalPath = Path { path in
  741. var yPoint: CGFloat = Config.basalHeight
  742. path.move(to: CGPoint(x: 0, y: yPoint))
  743. for point in tempBasalPoints {
  744. path.addLine(to: CGPoint(x: point.x, y: yPoint))
  745. path.addLine(to: point)
  746. yPoint = point.y
  747. }
  748. let lastPoint = lastBasalPoint(fullSize: fullSize)
  749. path.addLine(to: CGPoint(x: lastPoint.x, y: yPoint))
  750. path.addLine(to: CGPoint(x: lastPoint.x, y: Config.basalHeight))
  751. path.addLine(to: CGPoint(x: 0, y: Config.basalHeight))
  752. }
  753. let adjustForOptionalExtraHours = screenHours > 12 ? screenHours - 12 : 0
  754. let endDateTime = dayAgoTime + min(max(Int(screenHours - adjustForOptionalExtraHours), 12), 24).hours
  755. .timeInterval + min(max(Int(screenHours - adjustForOptionalExtraHours), 12), 24).hours
  756. .timeInterval
  757. let autotunedBasalPoints = findRegularBasalPoints(
  758. timeBegin: dayAgoTime,
  759. timeEnd: endDateTime,
  760. fullSize: fullSize,
  761. autotuned: true
  762. )
  763. let autotunedBasalPath = Path { path in
  764. var yPoint: CGFloat = Config.basalHeight
  765. path.move(to: CGPoint(x: -50, y: yPoint))
  766. for point in autotunedBasalPoints {
  767. path.addLine(to: CGPoint(x: point.x, y: yPoint))
  768. path.addLine(to: point)
  769. yPoint = point.y
  770. }
  771. path.addLine(to: CGPoint(x: timeToXCoordinate(endDateTime, fullSize: fullSize), y: yPoint))
  772. }
  773. DispatchQueue.main.async {
  774. self.tempBasalPath = tempBasalPath
  775. self.regularBasalPath = autotunedBasalPath
  776. }
  777. }
  778. }
  779. private func calculateSuspensions(fullSize: CGSize) {
  780. calculationQueue.async {
  781. var rects = suspensions.windows(ofCount: 2).map { window -> CGRect? in
  782. let window = Array(window)
  783. guard window[0].type == .pumpSuspend, window[1].type == .pumpResume else { return nil }
  784. let x0 = self.timeToXCoordinate(window[0].timestamp.timeIntervalSince1970, fullSize: fullSize)
  785. let x1 = self.timeToXCoordinate(window[1].timestamp.timeIntervalSince1970, fullSize: fullSize)
  786. return CGRect(x: x0, y: 0, width: x1 - x0, height: Config.basalHeight * 0.7)
  787. }
  788. let firstRec = self.suspensions.first.flatMap { event -> CGRect? in
  789. guard event.type == .pumpResume else { return nil }
  790. let tbrTime = self.tempBasals.last { $0.timestamp < event.timestamp }
  791. .map { $0.timestamp.timeIntervalSince1970 + TimeInterval($0.durationMin ?? 0) * 60 } ?? Date()
  792. .addingTimeInterval(-1.days.timeInterval).timeIntervalSince1970
  793. let x0 = self.timeToXCoordinate(tbrTime, fullSize: fullSize)
  794. let x1 = self.timeToXCoordinate(event.timestamp.timeIntervalSince1970, fullSize: fullSize)
  795. return CGRect(
  796. x: x0,
  797. y: 0,
  798. width: x1 - x0,
  799. height: Config.basalHeight * 0.7
  800. )
  801. }
  802. let lastRec = self.suspensions.last.flatMap { event -> CGRect? in
  803. guard event.type == .pumpSuspend else { return nil }
  804. let tbrTimeX = self.tempBasals.first { $0.timestamp > event.timestamp }
  805. .map { self.timeToXCoordinate($0.timestamp.timeIntervalSince1970, fullSize: fullSize) }
  806. let x0 = self.timeToXCoordinate(event.timestamp.timeIntervalSince1970, fullSize: fullSize)
  807. let x1 = tbrTimeX ?? self.fullGlucoseWidth(viewWidth: fullSize.width) + self
  808. .additionalWidth(viewWidth: fullSize.width)
  809. return CGRect(x: x0, y: 0, width: x1 - x0, height: Config.basalHeight * 0.7)
  810. }
  811. rects.append(firstRec)
  812. rects.append(lastRec)
  813. let path = Path { path in
  814. path.addRects(rects.compactMap { $0 })
  815. }
  816. DispatchQueue.main.async {
  817. suspensionsPath = path
  818. }
  819. }
  820. }
  821. private func maxBasalRate() -> Decimal {
  822. if let cached = cachedMaxBasalRate {
  823. return cached
  824. }
  825. let maxRegularBasalRate = max(
  826. basalProfile.map(\.rate).max() ?? maxBasal,
  827. autotunedBasalProfile.map(\.rate).max() ?? maxBasal
  828. )
  829. var maxTempBasalRate = tempBasals.compactMap(\.rate).max() ?? maxRegularBasalRate
  830. if maxTempBasalRate == 0 {
  831. maxTempBasalRate = maxRegularBasalRate
  832. }
  833. cachedMaxBasalRate = max(maxTempBasalRate, maxRegularBasalRate)
  834. return cachedMaxBasalRate ?? maxBasal
  835. }
  836. private func calculateTempTargetsRects(fullSize: CGSize) {
  837. calculationQueue.async {
  838. var rects = tempTargets.map { tempTarget -> CGRect in
  839. let x0 = timeToXCoordinate(tempTarget.createdAt.timeIntervalSince1970, fullSize: fullSize)
  840. let y0 = glucoseToYCoordinate(Int(tempTarget.targetTop ?? 0), fullSize: fullSize)
  841. let x1 = timeToXCoordinate(
  842. tempTarget.createdAt.timeIntervalSince1970 + Int(tempTarget.duration).minutes.timeInterval,
  843. fullSize: fullSize
  844. )
  845. let y1 = glucoseToYCoordinate(Int(tempTarget.targetBottom ?? 0), fullSize: fullSize)
  846. return CGRect(
  847. x: x0,
  848. y: y0 - 3,
  849. width: x1 - x0,
  850. height: y1 - y0 + 6
  851. )
  852. }
  853. if rects.count > 1 {
  854. rects = rects.reduce([]) { result, rect -> [CGRect] in
  855. guard var last = result.last else { return [rect] }
  856. if last.origin.x + last.width > rect.origin.x {
  857. last.size.width = rect.origin.x - last.origin.x
  858. }
  859. var res = Array(result.dropLast())
  860. res.append(contentsOf: [last, rect])
  861. return res
  862. }
  863. }
  864. let path = Path { path in
  865. path.addRects(rects)
  866. }
  867. DispatchQueue.main.async {
  868. tempTargetsPath = path
  869. }
  870. }
  871. }
  872. private func findRegularBasalPoints(
  873. timeBegin: TimeInterval,
  874. timeEnd: TimeInterval,
  875. fullSize: CGSize,
  876. autotuned: Bool
  877. ) -> [CGPoint] {
  878. guard timeBegin < timeEnd else {
  879. return []
  880. }
  881. let beginDate = Date(timeIntervalSince1970: timeBegin)
  882. let calendar = Calendar.current
  883. let startOfDay = calendar.startOfDay(for: beginDate)
  884. let profile = autotuned ? autotunedBasalProfile : basalProfile
  885. let basalNormalized = profile.map {
  886. (
  887. time: startOfDay.addingTimeInterval($0.minutes.minutes.timeInterval).timeIntervalSince1970,
  888. rate: $0.rate
  889. )
  890. } + profile.map {
  891. (
  892. time: startOfDay.addingTimeInterval($0.minutes.minutes.timeInterval + 1.days.timeInterval).timeIntervalSince1970,
  893. rate: $0.rate
  894. )
  895. } + profile.map {
  896. (
  897. time: startOfDay.addingTimeInterval($0.minutes.minutes.timeInterval + 2.days.timeInterval).timeIntervalSince1970,
  898. rate: $0.rate
  899. )
  900. }
  901. let basalTruncatedPoints = basalNormalized.windows(ofCount: 2)
  902. .compactMap { window -> CGPoint? in
  903. let window = Array(window)
  904. if window[0].time < timeBegin, window[1].time < timeBegin {
  905. return nil
  906. }
  907. let rateCost = Config.basalHeight / CGFloat(maxBasalRate())
  908. if window[0].time < timeBegin, window[1].time >= timeBegin {
  909. let x = timeToXCoordinate(timeBegin, fullSize: fullSize)
  910. let y = Config.basalHeight - CGFloat(window[0].rate) * rateCost
  911. return CGPoint(x: x, y: y)
  912. }
  913. if window[0].time >= timeBegin, window[0].time < timeEnd {
  914. let x = timeToXCoordinate(window[0].time, fullSize: fullSize)
  915. let y = Config.basalHeight - CGFloat(window[0].rate) * rateCost
  916. return CGPoint(x: x, y: y)
  917. }
  918. return nil
  919. }
  920. return basalTruncatedPoints
  921. }
  922. private func lastBasalPoint(fullSize: CGSize) -> CGPoint {
  923. let lastBasal = Array(tempBasals.suffix(2))
  924. guard lastBasal.count == 2 else {
  925. return CGPoint(x: timeToXCoordinate(Date().timeIntervalSince1970, fullSize: fullSize), y: Config.basalHeight)
  926. }
  927. let endBasalTime = lastBasal[0].timestamp.timeIntervalSince1970 + (lastBasal[1].durationMin?.minutes.timeInterval ?? 0)
  928. let rateCost = Config.basalHeight / CGFloat(maxBasalRate())
  929. let x = timeToXCoordinate(endBasalTime, fullSize: fullSize)
  930. let y = Config.basalHeight - CGFloat(lastBasal[0].rate ?? 0) * rateCost
  931. return CGPoint(x: x, y: y)
  932. }
  933. private func fullGlucoseWidth(viewWidth: CGFloat) -> CGFloat {
  934. viewWidth * CGFloat(hours) / CGFloat(min(max(screenHours, 2), 24))
  935. }
  936. private func additionalWidth(viewWidth: CGFloat) -> CGFloat {
  937. guard let predictions = suggestion?.predictions,
  938. let deliveredAt = suggestion?.deliverAt,
  939. let last = glucose.last
  940. else {
  941. return Config.minAdditionalWidth
  942. }
  943. let iob = predictions.iob?.count ?? 0
  944. let zt = predictions.zt?.count ?? 0
  945. let cob = predictions.cob?.count ?? 0
  946. let uam = predictions.uam?.count ?? 0
  947. let max = [iob, zt, cob, uam].max() ?? 0
  948. let lastDeltaTime = last.dateString.timeIntervalSince(deliveredAt)
  949. let additionalTime = CGFloat(TimeInterval(max) * 5.minutes.timeInterval - lastDeltaTime)
  950. let oneSecondWidth = oneSecondStep(viewWidth: viewWidth)
  951. return Swift.min(Swift.max(additionalTime * oneSecondWidth, Config.minAdditionalWidth), 275)
  952. }
  953. private func oneSecondStep(viewWidth: CGFloat) -> CGFloat {
  954. viewWidth / (CGFloat(min(max(screenHours, 2), 24)) * CGFloat(1.hours.timeInterval))
  955. }
  956. private func maxPredValue() -> Int? {
  957. [
  958. suggestion?.predictions?.cob ?? [],
  959. suggestion?.predictions?.iob ?? [],
  960. suggestion?.predictions?.zt ?? [],
  961. suggestion?.predictions?.uam ?? []
  962. ]
  963. .flatMap { $0 }
  964. .max()
  965. }
  966. private func minPredValue() -> Int? {
  967. [
  968. suggestion?.predictions?.cob ?? [],
  969. suggestion?.predictions?.iob ?? [],
  970. suggestion?.predictions?.zt ?? [],
  971. suggestion?.predictions?.uam ?? []
  972. ]
  973. .flatMap { $0 }
  974. .min()
  975. }
  976. private func maxTargetValue() -> Int? {
  977. tempTargets.map { $0.targetTop ?? 0 }.filter { $0 > 0 }.max().map(Int.init)
  978. }
  979. private func minTargetValue() -> Int? {
  980. tempTargets.map { $0.targetBottom ?? 0 }.filter { $0 > 0 }.min().map(Int.init)
  981. }
  982. private func glucoseToCoordinate(_ glucoseEntry: BloodGlucose, fullSize: CGSize) -> CGPoint {
  983. let x = timeToXCoordinate(glucoseEntry.dateString.timeIntervalSince1970, fullSize: fullSize)
  984. let y = glucoseToYCoordinate(glucoseEntry.glucose ?? 0, fullSize: fullSize)
  985. return CGPoint(x: x, y: y)
  986. }
  987. private func UnSmoothedGlucoseToCoordinate(_ glucoseEntry: BloodGlucose, fullSize: CGSize) -> CGPoint {
  988. let x = timeToXCoordinate(glucoseEntry.dateString.timeIntervalSince1970, fullSize: fullSize)
  989. let glucoseValue: Decimal = glucoseEntry.unfiltered ?? Decimal(glucoseEntry.glucose ?? 0)
  990. let y = glucoseToYCoordinate(Int(glucoseValue), fullSize: fullSize)
  991. return CGPoint(x: x, y: y)
  992. }
  993. private func predictionToCoordinate(_ pred: Int, fullSize: CGSize, index: Int) -> CGPoint {
  994. guard let deliveredAt = suggestion?.deliverAt else {
  995. return .zero
  996. }
  997. let predTime = deliveredAt.timeIntervalSince1970 + TimeInterval(index) * 5.minutes.timeInterval
  998. let x = timeToXCoordinate(predTime, fullSize: fullSize)
  999. let y = glucoseToYCoordinate(pred, fullSize: fullSize)
  1000. return CGPoint(x: x, y: y)
  1001. }
  1002. private func timeToXCoordinate(_ time: TimeInterval, fullSize: CGSize) -> CGFloat {
  1003. let xOffset = -Date().addingTimeInterval(-1.days.timeInterval).timeIntervalSince1970
  1004. let stepXFraction = fullGlucoseWidth(viewWidth: fullSize.width) / CGFloat(hours.hours.timeInterval)
  1005. let x = CGFloat(time + xOffset) * stepXFraction
  1006. return x
  1007. }
  1008. private func glucoseToYCoordinate(_ glucoseValue: Int, fullSize: CGSize) -> CGFloat {
  1009. let topYPaddint = Config.topYPadding + Config.basalHeight
  1010. let bottomYPadding = Config.bottomYPadding
  1011. let (minValue, maxValue) = minMaxYValues()
  1012. let stepYFraction = (fullSize.height - topYPaddint - bottomYPadding) / CGFloat(maxValue - minValue)
  1013. let yOffset = CGFloat(minValue) * stepYFraction
  1014. let y = fullSize.height - CGFloat(glucoseValue) * stepYFraction + yOffset - bottomYPadding
  1015. return y
  1016. }
  1017. private func timeToInterpolatedPoint(_ time: TimeInterval, fullSize: CGSize) -> CGPoint {
  1018. var nextIndex = 0
  1019. for (index, value) in glucose.enumerated() {
  1020. if value.dateString.timeIntervalSince1970 > time {
  1021. nextIndex = index
  1022. break
  1023. }
  1024. }
  1025. let x = timeToXCoordinate(time, fullSize: fullSize)
  1026. guard nextIndex > 0 else {
  1027. let lastY = glucoseToYCoordinate(glucose.last?.glucose ?? 0, fullSize: fullSize)
  1028. return CGPoint(x: x, y: lastY)
  1029. }
  1030. let prevX = timeToXCoordinate(glucose[nextIndex - 1].dateString.timeIntervalSince1970, fullSize: fullSize)
  1031. let prevY = glucoseToYCoordinate(glucose[nextIndex - 1].glucose ?? 0, fullSize: fullSize)
  1032. let nextX = timeToXCoordinate(glucose[nextIndex].dateString.timeIntervalSince1970, fullSize: fullSize)
  1033. let nextY = glucoseToYCoordinate(glucose[nextIndex].glucose ?? 0, fullSize: fullSize)
  1034. let delta = nextX - prevX
  1035. let fraction = (x - prevX) / delta
  1036. return pointInLine(CGPoint(x: prevX, y: prevY), CGPoint(x: nextX, y: nextY), fraction)
  1037. }
  1038. private func minMaxYValues() -> (min: Int, max: Int) {
  1039. var maxValue = glucose.compactMap(\.glucose).max() ?? Config.maxGlucose
  1040. if let maxPredValue = maxPredValue() {
  1041. maxValue = max(maxValue, maxPredValue)
  1042. }
  1043. if let maxTargetValue = maxTargetValue() {
  1044. maxValue = max(maxValue, maxTargetValue)
  1045. }
  1046. var minValue = glucose.compactMap(\.glucose).min() ?? Config.minGlucose
  1047. if let minPredValue = minPredValue() {
  1048. minValue = min(minValue, minPredValue)
  1049. }
  1050. if let minTargetValue = minTargetValue() {
  1051. minValue = min(minValue, minTargetValue)
  1052. }
  1053. if minValue == maxValue {
  1054. minValue = Config.minGlucose
  1055. maxValue = Config.maxGlucose
  1056. }
  1057. // fix the grah y-axis as long as the min and max BG values are within set borders
  1058. if minValue > Config.minGlucose {
  1059. minValue = Config.minGlucose
  1060. }
  1061. if maxValue < Config.maxGlucose {
  1062. maxValue = Config.maxGlucose
  1063. }
  1064. return (min: minValue, max: maxValue)
  1065. }
  1066. private func getGlucoseYRange(fullSize: CGSize) -> GlucoseYRange {
  1067. let topYPaddint = Config.topYPadding + Config.basalHeight
  1068. let bottomYPadding = Config.bottomYPadding
  1069. let (minValue, maxValue) = minMaxYValues()
  1070. let stepYFraction = (fullSize.height - topYPaddint - bottomYPadding) / CGFloat(maxValue - minValue)
  1071. let yOffset = CGFloat(minValue) * stepYFraction
  1072. let maxY = fullSize.height - CGFloat(minValue) * stepYFraction + yOffset - bottomYPadding
  1073. let minY = fullSize.height - CGFloat(maxValue) * stepYFraction + yOffset - bottomYPadding
  1074. return (minValue: minValue, minY: minY, maxValue: maxValue, maxY: maxY)
  1075. }
  1076. private func firstHourDate() -> Date {
  1077. let firstDate = Date().addingTimeInterval(-1.days.timeInterval)
  1078. return firstDate.dateTruncated(from: .minute)!
  1079. }
  1080. private func firstHourPosition(viewWidth: CGFloat) -> CGFloat {
  1081. let firstDate = Date().addingTimeInterval(-1.days.timeInterval)
  1082. let firstHour = firstHourDate()
  1083. let lastDeltaTime = firstHour.timeIntervalSince(firstDate)
  1084. let oneSecondWidth = oneSecondStep(viewWidth: viewWidth)
  1085. return oneSecondWidth * CGFloat(lastDeltaTime)
  1086. }
  1087. // MARK: WORKS....BUT MAYBE TIMEZONE PROBLEMS COULD OCCUR
  1088. // DEFINETELY SOMETHING FOR OUR TIMEZONE EXPERT.....
  1089. private func calculateTINS() -> String {
  1090. let date = Date()
  1091. let calendar = Calendar.current
  1092. let offset = screenHours
  1093. var offsetComponents = DateComponents()
  1094. // offsetComponents.hour = -offset.rawValue
  1095. offsetComponents.hour = -Int(offset)
  1096. let startTime = calendar.date(byAdding: offsetComponents, to: date)!
  1097. print("******************")
  1098. print("die voll krasse start time ist: \(startTime)")
  1099. let bolusesForCurrentDay = boluses.filter { $0.timestamp >= startTime && $0.type == .bolus }
  1100. let totalBolus = bolusesForCurrentDay.map { $0.amount ?? 0 }.reduce(0, +)
  1101. let roundedTotalBolus = Decimal(round(100 * Double(totalBolus)) / 100)
  1102. return "\(roundedTotalBolus) U"
  1103. }
  1104. }