BolusStateModel.swift 26 KB

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