BolusStateModel.swift 26 KB

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