BolusStateModel.swift 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696
  1. import CoreData
  2. import Foundation
  3. import LoopKit
  4. import SwiftUI
  5. import Swinject
  6. extension Bolus {
  7. final class StateModel: BaseStateModel<Provider> {
  8. @Injected() var unlockmanager: UnlockManager!
  9. @Injected() var apsManager: APSManager!
  10. @Injected() var broadcaster: Broadcaster!
  11. @Injected() var pumpHistoryStorage: PumpHistoryStorage!
  12. // added for bolus calculator
  13. @Injected() var settings: SettingsManager!
  14. @Injected() var nsManager: NightscoutManager!
  15. @Injected() var carbsStorage: CarbsStorage!
  16. @Injected() var glucoseStorage: GlucoseStorage!
  17. @Injected() var determinationStorage: DeterminationStorage!
  18. @Published var lowGlucose: Decimal = 4 / 0.0555
  19. @Published var highGlucose: Decimal = 10 / 0.0555
  20. @Published var predictions: Predictions?
  21. @Published var amount: Decimal = 0
  22. @Published var insulinRecommended: Decimal = 0
  23. @Published var insulinRequired: Decimal = 0
  24. @Published var units: GlucoseUnits = .mgdL
  25. @Published var percentage: Decimal = 0
  26. @Published var threshold: Decimal = 0
  27. @Published var maxBolus: Decimal = 0
  28. @Published var errorString: Decimal = 0
  29. @Published var evBG: Decimal = 0
  30. @Published var insulin: Decimal = 0
  31. @Published var isf: Decimal = 0
  32. @Published var error: Bool = false
  33. @Published var minGuardBG: Decimal = 0
  34. @Published var minDelta: Decimal = 0
  35. @Published var expectedDelta: Decimal = 0
  36. @Published var minPredBG: Decimal = 0
  37. @Published var waitForSuggestion: Bool = false
  38. @Published var carbRatio: Decimal = 0
  39. @Published var addButtonPressed: Bool = false
  40. var waitForSuggestionInitial: Bool = false
  41. // added for bolus calculator
  42. @Published var target: Decimal = 0
  43. @Published var cob: Int16 = 0
  44. @Published var iob: Decimal = 0
  45. @Published var currentBG: Decimal = 0
  46. @Published var fifteenMinInsulin: Decimal = 0
  47. @Published var deltaBG: Decimal = 0
  48. @Published var targetDifferenceInsulin: Decimal = 0
  49. @Published var targetDifference: Decimal = 0
  50. @Published var wholeCob: Decimal = 0
  51. @Published var wholeCobInsulin: Decimal = 0
  52. @Published var iobInsulinReduction: Decimal = 0
  53. @Published var wholeCalc: Decimal = 0
  54. @Published var insulinCalculated: Decimal = 0
  55. @Published var fraction: Decimal = 0
  56. @Published var useCalc: Bool = false
  57. @Published var basal: Decimal = 0
  58. @Published var fattyMeals: Bool = false
  59. @Published var fattyMealFactor: Decimal = 0
  60. @Published var useFattyMealCorrectionFactor: Bool = false
  61. @Published var displayPresets: Bool = true
  62. @Published var currentBasal: Decimal = 0
  63. @Published var sweetMeals: Bool = false
  64. @Published var sweetMealFactor: Decimal = 0
  65. @Published var useSuperBolus: Bool = false
  66. @Published var superBolusInsulin: Decimal = 0
  67. @Published var meal: [CarbsEntry]?
  68. @Published var carbs: Decimal = 0
  69. @Published var fat: Decimal = 0
  70. @Published var protein: Decimal = 0
  71. @Published var note: String = ""
  72. @Published var date = Date()
  73. @Published var carbsRequired: Decimal?
  74. @Published var useFPUconversion: Bool = false
  75. @Published var dish: String = ""
  76. @Published var selection: MealPresetStored?
  77. @Published var summation: [String] = []
  78. @Published var maxCarbs: Decimal = 0
  79. @Published var id_: String = ""
  80. @Published var summary: String = ""
  81. @Published var skipBolus: Bool = false
  82. @Published var externalInsulin: Bool = false
  83. @Published var showInfo: Bool = false
  84. @Published var glucoseFromPersistence: [GlucoseStored] = []
  85. @Published var determination: [OrefDetermination] = []
  86. @Published var preprocessedData: [(id: UUID, forecast: Forecast, forecastValue: ForecastValue)] = []
  87. @Published var predictionsForChart: Predictions?
  88. @Published var simulatedDetermination: Determination?
  89. @Published var minForecast: [Int] = []
  90. @Published var maxForecast: [Int] = []
  91. let now = Date.now
  92. let context = CoreDataStack.shared.persistentContainer.viewContext
  93. let backgroundContext = CoreDataStack.shared.newTaskContext()
  94. private var coreDataObserver: CoreDataObserver?
  95. typealias PumpEvent = PumpEventStored.EventType
  96. override func subscribe() {
  97. setupGlucoseNotification()
  98. coreDataObserver = CoreDataObserver()
  99. registerHandlers()
  100. Task {
  101. await updateForecasts()
  102. }
  103. setupGlucoseArray()
  104. setupDeterminationsArray()
  105. broadcaster.register(DeterminationObserver.self, observer: self)
  106. broadcaster.register(BolusFailureObserver.self, observer: self)
  107. units = settingsManager.settings.units
  108. percentage = settingsManager.settings.insulinReqPercentage
  109. maxBolus = provider.pumpSettings().maxBolus
  110. // added
  111. fraction = settings.settings.overrideFactor
  112. useCalc = settings.settings.useCalc
  113. fattyMeals = settings.settings.fattyMeals
  114. fattyMealFactor = settings.settings.fattyMealFactor
  115. sweetMeals = settings.settings.sweetMeals
  116. sweetMealFactor = settings.settings.sweetMealFactor
  117. displayPresets = settings.settings.displayPresets
  118. lowGlucose = settingsManager.settings.low
  119. highGlucose = settingsManager.settings.high
  120. maxCarbs = settings.settings.maxCarbs
  121. skipBolus = settingsManager.settings.skipBolusScreenAfterCarbs
  122. useFPUconversion = settingsManager.settings.useFPUconversion
  123. if waitForSuggestionInitial {
  124. Task {
  125. let ok = await apsManager.determineBasal()
  126. if !ok {
  127. self.waitForSuggestion = false
  128. self.insulinRequired = 0
  129. self.insulinRecommended = 0
  130. }
  131. }
  132. }
  133. }
  134. // MARK: - Basal
  135. func getCurrentBasal() {
  136. let basalEntries = provider.getProfile()
  137. let now = Date()
  138. let calendar = Calendar.current
  139. let dateFormatter = DateFormatter()
  140. dateFormatter.dateFormat = "HH:mm:ss"
  141. dateFormatter.timeZone = TimeZone.current
  142. for (index, entry) in basalEntries.enumerated() {
  143. guard let entryTime = dateFormatter.date(from: entry.start) else {
  144. print("Invalid entry start time: \(entry.start)")
  145. continue
  146. }
  147. // Combine the current date with the time from entry.start
  148. let entryStartTime = calendar.date(
  149. bySettingHour: calendar.component(.hour, from: entryTime),
  150. minute: calendar.component(.minute, from: entryTime),
  151. second: calendar.component(.second, from: entryTime),
  152. of: now
  153. )!
  154. let entryEndTime: Date
  155. if index < basalEntries.count - 1,
  156. let nextEntryTime = dateFormatter.date(from: basalEntries[index + 1].start)
  157. {
  158. let nextEntryStartTime = calendar.date(
  159. bySettingHour: calendar.component(.hour, from: nextEntryTime),
  160. minute: calendar.component(.minute, from: nextEntryTime),
  161. second: calendar.component(.second, from: nextEntryTime),
  162. of: now
  163. )!
  164. entryEndTime = nextEntryStartTime
  165. } else {
  166. // If it's the last entry, use the same start time plus one day as the end time
  167. entryEndTime = calendar.date(byAdding: .day, value: 1, to: entryStartTime)!
  168. }
  169. if now >= entryStartTime, now < entryEndTime {
  170. currentBasal = entry.rate
  171. break
  172. }
  173. }
  174. }
  175. // MARK: CALCULATIONS FOR THE BOLUS CALCULATOR
  176. /// Calculate insulin recommendation
  177. func calculateInsulin() -> Decimal {
  178. // ensure that isf is in mg/dL
  179. var conversion: Decimal {
  180. units == .mmolL ? 0.0555 : 1
  181. }
  182. let isfForCalculation = isf / conversion
  183. // insulin needed for the current blood glucose
  184. targetDifference = currentBG - target
  185. targetDifferenceInsulin = targetDifference / isfForCalculation
  186. // more or less insulin because of bg trend in the last 15 minutes
  187. fifteenMinInsulin = deltaBG / isfForCalculation
  188. // determine whole COB for which we want to dose insulin for and then determine insulin for wholeCOB
  189. wholeCob = Decimal(cob) + carbs
  190. wholeCobInsulin = wholeCob / carbRatio
  191. // determine how much the calculator reduces/ increases the bolus because of IOB
  192. iobInsulinReduction = (-1) * iob
  193. // adding everything together
  194. // add a calc for the case that no fifteenMinInsulin is available
  195. if deltaBG != 0 {
  196. wholeCalc = (targetDifferenceInsulin + iobInsulinReduction + wholeCobInsulin + fifteenMinInsulin)
  197. } else {
  198. // add (rare) case that no glucose value is available -> maybe display warning?
  199. // if no bg is available, ?? sets its value to 0
  200. if currentBG == 0 {
  201. wholeCalc = (iobInsulinReduction + wholeCobInsulin)
  202. } else {
  203. wholeCalc = (targetDifferenceInsulin + iobInsulinReduction + wholeCobInsulin)
  204. }
  205. }
  206. // apply custom factor at the end of the calculations
  207. let result = wholeCalc * fraction
  208. // apply custom factor if fatty meal toggle in bolus calc config settings is on and the box for fatty meals is checked (in RootView)
  209. if useFattyMealCorrectionFactor {
  210. insulinCalculated = result * fattyMealFactor
  211. } else if useSuperBolus {
  212. superBolusInsulin = sweetMealFactor * currentBasal
  213. insulinCalculated = result + superBolusInsulin
  214. } else {
  215. insulinCalculated = result
  216. }
  217. // display no negative insulinCalculated
  218. insulinCalculated = max(insulinCalculated, 0)
  219. insulinCalculated = min(insulinCalculated, maxBolus)
  220. guard let apsManager = apsManager else {
  221. debug(.apsManager, "APSManager could not be gracefully unwrapped")
  222. return insulinCalculated
  223. }
  224. return apsManager.roundBolus(amount: insulinCalculated)
  225. }
  226. // MARK: - Button tasks
  227. @MainActor func invokeTreatmentsTask() {
  228. Task {
  229. addButtonPressed = true
  230. let isInsulinGiven = amount > 0
  231. let isCarbsPresent = carbs > 0
  232. let isFatPresent = fat > 0
  233. let isProteinPresent = protein > 0
  234. if isInsulinGiven {
  235. try await handleInsulin(isExternal: externalInsulin)
  236. } else if isCarbsPresent || isFatPresent || isProteinPresent {
  237. waitForSuggestion = true
  238. } else {
  239. hideModal()
  240. return
  241. }
  242. await saveMeal()
  243. // if glucose data is stale end the custom loading animation by hiding the modal
  244. // guard glucoseOfLast20Min.first?.date ?? now >= Date().addingTimeInterval(-12.minutes.timeInterval) else {
  245. // return hideModal()
  246. // }
  247. }
  248. }
  249. // MARK: - Insulin
  250. @MainActor private func handleInsulin(isExternal: Bool) async throws {
  251. if !isExternal {
  252. await addPumpInsulin()
  253. } else {
  254. await addExternalInsulin()
  255. }
  256. waitForSuggestion = true
  257. }
  258. @MainActor func addPumpInsulin() async {
  259. guard amount > 0 else {
  260. showModal(for: nil)
  261. return
  262. }
  263. let maxAmount = Double(min(amount, maxBolus))
  264. do {
  265. let authenticated = try await unlockmanager.unlock()
  266. if authenticated {
  267. await apsManager.enactBolus(amount: maxAmount, isSMB: false)
  268. } else {
  269. print("authentication failed")
  270. }
  271. } catch {
  272. print("authentication error for pump bolus: \(error.localizedDescription)")
  273. DispatchQueue.main.async {
  274. self.waitForSuggestion = false
  275. if self.addButtonPressed {
  276. self.hideModal()
  277. }
  278. }
  279. }
  280. }
  281. private func savePumpInsulin(amount _: Decimal) {
  282. context.perform {
  283. // create pump event
  284. let newPumpEvent = PumpEventStored(context: self.context)
  285. newPumpEvent.timestamp = Date()
  286. newPumpEvent.type = PumpEvent.bolus.rawValue
  287. // create bolus entry and specify relationship to pump event
  288. let newBolusEntry = BolusStored(context: self.context)
  289. newBolusEntry.pumpEvent = newPumpEvent
  290. newBolusEntry.amount = self.amount as NSDecimalNumber
  291. newBolusEntry.isExternal = false
  292. newBolusEntry.isSMB = false
  293. do {
  294. guard self.context.hasChanges else { return }
  295. try self.context.save()
  296. } catch {
  297. print(error.localizedDescription)
  298. }
  299. }
  300. }
  301. // MARK: - EXTERNAL INSULIN
  302. @MainActor func addExternalInsulin() async {
  303. guard amount > 0 else {
  304. showModal(for: nil)
  305. return
  306. }
  307. amount = min(amount, maxBolus * 3)
  308. do {
  309. let authenticated = try await unlockmanager.unlock()
  310. if authenticated {
  311. // store external dose to pump history
  312. await pumpHistoryStorage.storeExternalInsulinEvent(amount: amount, timestamp: date)
  313. // perform determine basal sync
  314. await apsManager.determineBasalSync()
  315. } else {
  316. print("authentication failed")
  317. }
  318. } catch {
  319. print("authentication error for external insulin: \(error.localizedDescription)")
  320. DispatchQueue.main.async {
  321. self.waitForSuggestion = false
  322. if self.addButtonPressed {
  323. self.hideModal()
  324. }
  325. }
  326. }
  327. }
  328. // MARK: - Carbs
  329. @MainActor func saveMeal() async {
  330. guard carbs > 0 || fat > 0 || protein > 0 else { return }
  331. carbs = min(carbs, maxCarbs)
  332. id_ = UUID().uuidString
  333. let carbsToStore = [CarbsEntry(
  334. id: id_,
  335. createdAt: now,
  336. actualDate: date,
  337. carbs: carbs,
  338. fat: fat,
  339. protein: protein,
  340. note: note,
  341. enteredBy: CarbsEntry.manual,
  342. isFPU: false, fpuID: UUID().uuidString
  343. )]
  344. await carbsStorage.storeCarbs(carbsToStore)
  345. if carbs > 0 || fat > 0 || protein > 0 {
  346. // only perform determine basal sync if the user doesn't use the pump bolus, otherwise the enact bolus func in the APSManger does a sync
  347. if amount <= 0 {
  348. await apsManager.determineBasalSync()
  349. }
  350. }
  351. }
  352. // MARK: - Presets
  353. func deletePreset() {
  354. if selection != nil {
  355. context.delete(selection!)
  356. do {
  357. guard context.hasChanges else { return }
  358. try context.save()
  359. } catch {
  360. print(error.localizedDescription)
  361. }
  362. carbs = 0
  363. fat = 0
  364. protein = 0
  365. }
  366. selection = nil
  367. }
  368. func removePresetFromNewMeal() {
  369. let a = summation.firstIndex(where: { $0 == selection?.dish! })
  370. if a != nil, summation[a ?? 0] != "" {
  371. summation.remove(at: a!)
  372. }
  373. }
  374. func addPresetToNewMeal() {
  375. let test: String = selection?.dish ?? "dontAdd"
  376. if test != "dontAdd" {
  377. summation.append(test)
  378. }
  379. }
  380. func addNewPresetToWaitersNotepad(_ dish: String) {
  381. summation.append(dish)
  382. }
  383. func addToSummation() {
  384. summation.append(selection?.dish ?? "")
  385. }
  386. func waitersNotepad() -> String {
  387. var filteredArray = summation.filter { !$0.isEmpty }
  388. if carbs == 0, protein == 0, fat == 0 {
  389. filteredArray = []
  390. }
  391. guard filteredArray != [] else {
  392. return ""
  393. }
  394. var carbs_: Decimal = 0.0
  395. var fat_: Decimal = 0.0
  396. var protein_: Decimal = 0.0
  397. var presetArray = [MealPresetStored]()
  398. context.performAndWait {
  399. let requestPresets = MealPresetStored.fetchRequest() as NSFetchRequest<MealPresetStored>
  400. try? presetArray = context.fetch(requestPresets)
  401. }
  402. var waitersNotepad = [String]()
  403. var stringValue = ""
  404. for each in filteredArray {
  405. let countedSet = NSCountedSet(array: filteredArray)
  406. let count = countedSet.count(for: each)
  407. if each != stringValue {
  408. waitersNotepad.append("\(count) \(each)")
  409. }
  410. stringValue = each
  411. for sel in presetArray {
  412. if sel.dish == each {
  413. carbs_ += (sel.carbs)! as Decimal
  414. fat_ += (sel.fat)! as Decimal
  415. protein_ += (sel.protein)! as Decimal
  416. break
  417. }
  418. }
  419. }
  420. let extracarbs = carbs - carbs_
  421. let extraFat = fat - fat_
  422. let extraProtein = protein - protein_
  423. var addedString = ""
  424. if extracarbs > 0, filteredArray.isNotEmpty {
  425. addedString += "Additional carbs: \(extracarbs) ,"
  426. } else if extracarbs < 0 { addedString += "Removed carbs: \(extracarbs) " }
  427. if extraFat > 0, filteredArray.isNotEmpty {
  428. addedString += "Additional fat: \(extraFat) ,"
  429. } else if extraFat < 0 { addedString += "Removed fat: \(extraFat) ," }
  430. if extraProtein > 0, filteredArray.isNotEmpty {
  431. addedString += "Additional protein: \(extraProtein) ,"
  432. } else if extraProtein < 0 { addedString += "Removed protein: \(extraProtein) ," }
  433. if addedString != "" {
  434. waitersNotepad.append(addedString)
  435. }
  436. var waitersNotepadString = ""
  437. if waitersNotepad.count == 1 {
  438. waitersNotepadString = waitersNotepad[0]
  439. } else if waitersNotepad.count > 1 {
  440. for each in waitersNotepad {
  441. if each != waitersNotepad.last {
  442. waitersNotepadString += " " + each + ","
  443. } else { waitersNotepadString += " " + each }
  444. }
  445. }
  446. return waitersNotepadString
  447. }
  448. }
  449. }
  450. extension Bolus.StateModel: DeterminationObserver, BolusFailureObserver {
  451. func determinationDidUpdate(_: Determination) {
  452. DispatchQueue.main.async {
  453. self.waitForSuggestion = false
  454. if self.addButtonPressed {
  455. self.hideModal()
  456. }
  457. }
  458. }
  459. func bolusDidFail() {
  460. DispatchQueue.main.async {
  461. self.waitForSuggestion = false
  462. if self.addButtonPressed {
  463. self.hideModal()
  464. }
  465. }
  466. }
  467. }
  468. extension Bolus.StateModel {
  469. private func registerHandlers() {
  470. coreDataObserver?.registerHandler(for: "OrefDetermination") { [weak self] in
  471. guard let self = self else { return }
  472. self.setupDeterminationsArray()
  473. }
  474. // Due to the Batch insert this only is used for observing Deletion of Glucose entries
  475. coreDataObserver?.registerHandler(for: "GlucoseStored") { [weak self] in
  476. guard let self = self else { return }
  477. self.setupGlucoseArray()
  478. }
  479. }
  480. private func setupGlucoseNotification() {
  481. /// custom notification that is sent when a batch insert of glucose objects is done
  482. Foundation.NotificationCenter.default.addObserver(
  483. self,
  484. selector: #selector(handleBatchInsert),
  485. name: .didPerformBatchInsert,
  486. object: nil
  487. )
  488. }
  489. @objc private func handleBatchInsert() {
  490. setupGlucoseArray()
  491. }
  492. }
  493. // MARK: - Setup Glucose and Determinations
  494. extension Bolus.StateModel {
  495. // Glucose
  496. private func setupGlucoseArray() {
  497. Task {
  498. let ids = await self.fetchGlucose()
  499. await updateGlucoseArray(with: ids)
  500. }
  501. }
  502. private func fetchGlucose() async -> [NSManagedObjectID] {
  503. let results = await CoreDataStack.shared.fetchEntitiesAsync(
  504. ofType: GlucoseStored.self,
  505. onContext: backgroundContext,
  506. predicate: NSPredicate.predicateForFourHoursAgo,
  507. key: "date",
  508. ascending: false,
  509. fetchLimit: 48
  510. )
  511. return await backgroundContext.perform {
  512. return results.map(\.objectID)
  513. }
  514. }
  515. @MainActor private func updateGlucoseArray(with IDs: [NSManagedObjectID]) {
  516. do {
  517. let glucoseObjects = try IDs.compactMap { id in
  518. try context.existingObject(with: id) as? GlucoseStored
  519. }
  520. glucoseFromPersistence = glucoseObjects
  521. let lastGlucose = glucoseFromPersistence.first?.glucose ?? 0
  522. let thirdLastGlucose = glucoseFromPersistence.dropFirst(2).first?.glucose ?? 0
  523. let delta = Decimal(lastGlucose) - Decimal(thirdLastGlucose)
  524. currentBG = Decimal(lastGlucose)
  525. deltaBG = delta
  526. } catch {
  527. debugPrint(
  528. "Home State: \(#function) \(DebuggingIdentifiers.failed) error while updating the glucose array: \(error.localizedDescription)"
  529. )
  530. }
  531. }
  532. // Determinations
  533. private func setupDeterminationsArray() {
  534. Task {
  535. let ids = await determinationStorage.fetchLastDeterminationObjectID(
  536. predicate: NSPredicate.enactedDetermination
  537. )
  538. await updateDeterminationsArray(with: ids)
  539. await updateForecasts()
  540. }
  541. }
  542. @MainActor private func updateDeterminationsArray(with IDs: [NSManagedObjectID]) {
  543. do {
  544. let determinationObjects = try IDs.compactMap { id in
  545. try context.existingObject(with: id) as? OrefDetermination
  546. }
  547. guard let mostRecentDetermination = determinationObjects.first else { return }
  548. determination = determinationObjects
  549. // setup vars for bolus calculation
  550. insulinRequired = (mostRecentDetermination.insulinReq ?? 0) as Decimal
  551. evBG = (mostRecentDetermination.eventualBG ?? 0) as Decimal
  552. insulin = (mostRecentDetermination.insulinForManualBolus ?? 0) as Decimal
  553. target = (mostRecentDetermination.currentTarget ?? 100) as Decimal
  554. isf = (mostRecentDetermination.insulinSensitivity ?? 0) as Decimal
  555. cob = mostRecentDetermination.cob as Int16
  556. iob = (mostRecentDetermination.iob ?? 0) as Decimal
  557. basal = (mostRecentDetermination.tempBasal ?? 0) as Decimal
  558. carbRatio = (mostRecentDetermination.carbRatio ?? 0) as Decimal
  559. getCurrentBasal()
  560. insulinCalculated = calculateInsulin()
  561. } catch {
  562. debugPrint(
  563. "Home State: \(#function) \(DebuggingIdentifiers.failed) error while updating the determinations array: \(error.localizedDescription)"
  564. )
  565. }
  566. }
  567. }
  568. extension Bolus.StateModel {
  569. @MainActor func updateForecasts() async {
  570. simulatedDetermination = await apsManager.simulateDetermineBasal(carbs: carbs, iob: amount)
  571. predictionsForChart = simulatedDetermination?.predictions
  572. let iob: [Int] = predictionsForChart?.iob ?? []
  573. let zt: [Int] = predictionsForChart?.zt ?? []
  574. let cob: [Int] = predictionsForChart?.cob ?? []
  575. let uam: [Int] = predictionsForChart?.uam ?? []
  576. // Filter out the empty arrays and find the maximum length of the remaining arrays
  577. let nonEmptyArrays: [[Int]] = [iob, zt, cob, uam].filter { !$0.isEmpty }
  578. guard !nonEmptyArrays.isEmpty, let maxCount = nonEmptyArrays.map(\.count).max(), maxCount > 0 else {
  579. minForecast = []
  580. maxForecast = []
  581. return
  582. }
  583. minForecast = (0 ..< maxCount).map { index -> Int in
  584. let valuesAtCurrentIndex = nonEmptyArrays.compactMap { $0.indices.contains(index) ? $0[index] : nil }
  585. return valuesAtCurrentIndex.min() ?? 0
  586. }
  587. maxForecast = (0 ..< maxCount).map { index -> Int in
  588. let valuesAtCurrentIndex = nonEmptyArrays.compactMap { $0.indices.contains(index) ? $0[index] : nil }
  589. return valuesAtCurrentIndex.max() ?? 0
  590. }
  591. }
  592. }