MainChartView.swift 48 KB

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