BolusStateModel.swift 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697
  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 glucoseStorage.isGlucoseDataFresh(glucoseFromPersistence.first?.date) else {
  245. waitForSuggestion = false
  246. return hideModal()
  247. }
  248. }
  249. }
  250. // MARK: - Insulin
  251. @MainActor private func handleInsulin(isExternal: Bool) async throws {
  252. if !isExternal {
  253. await addPumpInsulin()
  254. } else {
  255. await addExternalInsulin()
  256. }
  257. waitForSuggestion = true
  258. }
  259. @MainActor func addPumpInsulin() async {
  260. guard amount > 0 else {
  261. showModal(for: nil)
  262. return
  263. }
  264. let maxAmount = Double(min(amount, maxBolus))
  265. do {
  266. let authenticated = try await unlockmanager.unlock()
  267. if authenticated {
  268. await apsManager.enactBolus(amount: maxAmount, isSMB: false)
  269. } else {
  270. print("authentication failed")
  271. }
  272. } catch {
  273. print("authentication error for pump bolus: \(error.localizedDescription)")
  274. DispatchQueue.main.async {
  275. self.waitForSuggestion = false
  276. if self.addButtonPressed {
  277. self.hideModal()
  278. }
  279. }
  280. }
  281. }
  282. private func savePumpInsulin(amount _: Decimal) {
  283. context.perform {
  284. // create pump event
  285. let newPumpEvent = PumpEventStored(context: self.context)
  286. newPumpEvent.timestamp = Date()
  287. newPumpEvent.type = PumpEvent.bolus.rawValue
  288. // create bolus entry and specify relationship to pump event
  289. let newBolusEntry = BolusStored(context: self.context)
  290. newBolusEntry.pumpEvent = newPumpEvent
  291. newBolusEntry.amount = self.amount as NSDecimalNumber
  292. newBolusEntry.isExternal = false
  293. newBolusEntry.isSMB = false
  294. do {
  295. guard self.context.hasChanges else { return }
  296. try self.context.save()
  297. } catch {
  298. print(error.localizedDescription)
  299. }
  300. }
  301. }
  302. // MARK: - EXTERNAL INSULIN
  303. @MainActor func addExternalInsulin() async {
  304. guard amount > 0 else {
  305. showModal(for: nil)
  306. return
  307. }
  308. amount = min(amount, maxBolus * 3)
  309. do {
  310. let authenticated = try await unlockmanager.unlock()
  311. if authenticated {
  312. // store external dose to pump history
  313. await pumpHistoryStorage.storeExternalInsulinEvent(amount: amount, timestamp: date)
  314. // perform determine basal sync
  315. await apsManager.determineBasalSync()
  316. } else {
  317. print("authentication failed")
  318. }
  319. } catch {
  320. print("authentication error for external insulin: \(error.localizedDescription)")
  321. DispatchQueue.main.async {
  322. self.waitForSuggestion = false
  323. if self.addButtonPressed {
  324. self.hideModal()
  325. }
  326. }
  327. }
  328. }
  329. // MARK: - Carbs
  330. @MainActor func saveMeal() async {
  331. guard carbs > 0 || fat > 0 || protein > 0 else { return }
  332. carbs = min(carbs, maxCarbs)
  333. id_ = UUID().uuidString
  334. let carbsToStore = [CarbsEntry(
  335. id: id_,
  336. createdAt: now,
  337. actualDate: date,
  338. carbs: carbs,
  339. fat: fat,
  340. protein: protein,
  341. note: note,
  342. enteredBy: CarbsEntry.manual,
  343. isFPU: false, fpuID: UUID().uuidString
  344. )]
  345. await carbsStorage.storeCarbs(carbsToStore)
  346. if carbs > 0 || fat > 0 || protein > 0 {
  347. // 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
  348. if amount <= 0 {
  349. await apsManager.determineBasalSync()
  350. }
  351. }
  352. }
  353. // MARK: - Presets
  354. func deletePreset() {
  355. if selection != nil {
  356. context.delete(selection!)
  357. do {
  358. guard context.hasChanges else { return }
  359. try context.save()
  360. } catch {
  361. print(error.localizedDescription)
  362. }
  363. carbs = 0
  364. fat = 0
  365. protein = 0
  366. }
  367. selection = nil
  368. }
  369. func removePresetFromNewMeal() {
  370. let a = summation.firstIndex(where: { $0 == selection?.dish! })
  371. if a != nil, summation[a ?? 0] != "" {
  372. summation.remove(at: a!)
  373. }
  374. }
  375. func addPresetToNewMeal() {
  376. let test: String = selection?.dish ?? "dontAdd"
  377. if test != "dontAdd" {
  378. summation.append(test)
  379. }
  380. }
  381. func addNewPresetToWaitersNotepad(_ dish: String) {
  382. summation.append(dish)
  383. }
  384. func addToSummation() {
  385. summation.append(selection?.dish ?? "")
  386. }
  387. func waitersNotepad() -> String {
  388. var filteredArray = summation.filter { !$0.isEmpty }
  389. if carbs == 0, protein == 0, fat == 0 {
  390. filteredArray = []
  391. }
  392. guard filteredArray != [] else {
  393. return ""
  394. }
  395. var carbs_: Decimal = 0.0
  396. var fat_: Decimal = 0.0
  397. var protein_: Decimal = 0.0
  398. var presetArray = [MealPresetStored]()
  399. context.performAndWait {
  400. let requestPresets = MealPresetStored.fetchRequest() as NSFetchRequest<MealPresetStored>
  401. try? presetArray = context.fetch(requestPresets)
  402. }
  403. var waitersNotepad = [String]()
  404. var stringValue = ""
  405. for each in filteredArray {
  406. let countedSet = NSCountedSet(array: filteredArray)
  407. let count = countedSet.count(for: each)
  408. if each != stringValue {
  409. waitersNotepad.append("\(count) \(each)")
  410. }
  411. stringValue = each
  412. for sel in presetArray {
  413. if sel.dish == each {
  414. carbs_ += (sel.carbs)! as Decimal
  415. fat_ += (sel.fat)! as Decimal
  416. protein_ += (sel.protein)! as Decimal
  417. break
  418. }
  419. }
  420. }
  421. let extracarbs = carbs - carbs_
  422. let extraFat = fat - fat_
  423. let extraProtein = protein - protein_
  424. var addedString = ""
  425. if extracarbs > 0, filteredArray.isNotEmpty {
  426. addedString += "Additional carbs: \(extracarbs) ,"
  427. } else if extracarbs < 0 { addedString += "Removed carbs: \(extracarbs) " }
  428. if extraFat > 0, filteredArray.isNotEmpty {
  429. addedString += "Additional fat: \(extraFat) ,"
  430. } else if extraFat < 0 { addedString += "Removed fat: \(extraFat) ," }
  431. if extraProtein > 0, filteredArray.isNotEmpty {
  432. addedString += "Additional protein: \(extraProtein) ,"
  433. } else if extraProtein < 0 { addedString += "Removed protein: \(extraProtein) ," }
  434. if addedString != "" {
  435. waitersNotepad.append(addedString)
  436. }
  437. var waitersNotepadString = ""
  438. if waitersNotepad.count == 1 {
  439. waitersNotepadString = waitersNotepad[0]
  440. } else if waitersNotepad.count > 1 {
  441. for each in waitersNotepad {
  442. if each != waitersNotepad.last {
  443. waitersNotepadString += " " + each + ","
  444. } else { waitersNotepadString += " " + each }
  445. }
  446. }
  447. return waitersNotepadString
  448. }
  449. }
  450. }
  451. extension Bolus.StateModel: DeterminationObserver, BolusFailureObserver {
  452. func determinationDidUpdate(_: Determination) {
  453. DispatchQueue.main.async {
  454. self.waitForSuggestion = false
  455. if self.addButtonPressed {
  456. self.hideModal()
  457. }
  458. }
  459. }
  460. func bolusDidFail() {
  461. DispatchQueue.main.async {
  462. self.waitForSuggestion = false
  463. if self.addButtonPressed {
  464. self.hideModal()
  465. }
  466. }
  467. }
  468. }
  469. extension Bolus.StateModel {
  470. private func registerHandlers() {
  471. coreDataObserver?.registerHandler(for: "OrefDetermination") { [weak self] in
  472. guard let self = self else { return }
  473. self.setupDeterminationsArray()
  474. }
  475. // Due to the Batch insert this only is used for observing Deletion of Glucose entries
  476. coreDataObserver?.registerHandler(for: "GlucoseStored") { [weak self] in
  477. guard let self = self else { return }
  478. self.setupGlucoseArray()
  479. }
  480. }
  481. private func setupGlucoseNotification() {
  482. /// custom notification that is sent when a batch insert of glucose objects is done
  483. Foundation.NotificationCenter.default.addObserver(
  484. self,
  485. selector: #selector(handleBatchInsert),
  486. name: .didPerformBatchInsert,
  487. object: nil
  488. )
  489. }
  490. @objc private func handleBatchInsert() {
  491. setupGlucoseArray()
  492. }
  493. }
  494. // MARK: - Setup Glucose and Determinations
  495. extension Bolus.StateModel {
  496. // Glucose
  497. private func setupGlucoseArray() {
  498. Task {
  499. let ids = await self.fetchGlucose()
  500. await updateGlucoseArray(with: ids)
  501. }
  502. }
  503. private func fetchGlucose() async -> [NSManagedObjectID] {
  504. let results = await CoreDataStack.shared.fetchEntitiesAsync(
  505. ofType: GlucoseStored.self,
  506. onContext: backgroundContext,
  507. predicate: NSPredicate.predicateForFourHoursAgo,
  508. key: "date",
  509. ascending: false,
  510. fetchLimit: 48
  511. )
  512. return await backgroundContext.perform {
  513. return results.map(\.objectID)
  514. }
  515. }
  516. @MainActor private func updateGlucoseArray(with IDs: [NSManagedObjectID]) {
  517. do {
  518. let glucoseObjects = try IDs.compactMap { id in
  519. try context.existingObject(with: id) as? GlucoseStored
  520. }
  521. glucoseFromPersistence = glucoseObjects
  522. let lastGlucose = glucoseFromPersistence.first?.glucose ?? 0
  523. let thirdLastGlucose = glucoseFromPersistence.dropFirst(2).first?.glucose ?? 0
  524. let delta = Decimal(lastGlucose) - Decimal(thirdLastGlucose)
  525. currentBG = Decimal(lastGlucose)
  526. deltaBG = delta
  527. } catch {
  528. debugPrint(
  529. "Home State: \(#function) \(DebuggingIdentifiers.failed) error while updating the glucose array: \(error.localizedDescription)"
  530. )
  531. }
  532. }
  533. // Determinations
  534. private func setupDeterminationsArray() {
  535. Task {
  536. let ids = await determinationStorage.fetchLastDeterminationObjectID(
  537. predicate: NSPredicate.predicateFor30MinAgoForDetermination
  538. )
  539. await updateDeterminationsArray(with: ids)
  540. await updateForecasts()
  541. }
  542. }
  543. @MainActor private func updateDeterminationsArray(with IDs: [NSManagedObjectID]) {
  544. do {
  545. let determinationObjects = try IDs.compactMap { id in
  546. try context.existingObject(with: id) as? OrefDetermination
  547. }
  548. guard let mostRecentDetermination = determinationObjects.first else { return }
  549. determination = determinationObjects
  550. // setup vars for bolus calculation
  551. insulinRequired = (mostRecentDetermination.insulinReq ?? 0) as Decimal
  552. evBG = (mostRecentDetermination.eventualBG ?? 0) as Decimal
  553. insulin = (mostRecentDetermination.insulinForManualBolus ?? 0) as Decimal
  554. target = (mostRecentDetermination.currentTarget ?? 100) as Decimal
  555. isf = (mostRecentDetermination.insulinSensitivity ?? 0) as Decimal
  556. cob = mostRecentDetermination.cob as Int16
  557. iob = (mostRecentDetermination.iob ?? 0) as Decimal
  558. basal = (mostRecentDetermination.tempBasal ?? 0) as Decimal
  559. carbRatio = (mostRecentDetermination.carbRatio ?? 0) as Decimal
  560. getCurrentBasal()
  561. insulinCalculated = calculateInsulin()
  562. } catch {
  563. debugPrint(
  564. "Home State: \(#function) \(DebuggingIdentifiers.failed) error while updating the determinations array: \(error.localizedDescription)"
  565. )
  566. }
  567. }
  568. }
  569. extension Bolus.StateModel {
  570. @MainActor func updateForecasts() async {
  571. simulatedDetermination = await apsManager.simulateDetermineBasal(carbs: carbs, iob: amount)
  572. predictionsForChart = simulatedDetermination?.predictions
  573. let iob: [Int] = predictionsForChart?.iob ?? []
  574. let zt: [Int] = predictionsForChart?.zt ?? []
  575. let cob: [Int] = predictionsForChart?.cob ?? []
  576. let uam: [Int] = predictionsForChart?.uam ?? []
  577. // Filter out the empty arrays and find the maximum length of the remaining arrays
  578. let nonEmptyArrays: [[Int]] = [iob, zt, cob, uam].filter { !$0.isEmpty }
  579. guard !nonEmptyArrays.isEmpty, let maxCount = nonEmptyArrays.map(\.count).max(), maxCount > 0 else {
  580. minForecast = []
  581. maxForecast = []
  582. return
  583. }
  584. minForecast = (0 ..< maxCount).map { index -> Int in
  585. let valuesAtCurrentIndex = nonEmptyArrays.compactMap { $0.indices.contains(index) ? $0[index] : nil }
  586. return valuesAtCurrentIndex.min() ?? 0
  587. }
  588. maxForecast = (0 ..< maxCount).map { index -> Int in
  589. let valuesAtCurrentIndex = nonEmptyArrays.compactMap { $0.indices.contains(index) ? $0[index] : nil }
  590. return valuesAtCurrentIndex.max() ?? 0
  591. }
  592. }
  593. }