PumpHistorySetup.swift 2.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. import CoreData
  2. import Foundation
  3. extension Home.StateModel {
  4. func setupInsulinArray() {
  5. Task {
  6. let ids = await self.fetchInsulin()
  7. let insulinObjects: [PumpEventStored] = await CoreDataStack.shared.getNSManagedObject(with: ids, context: viewContext)
  8. await updateInsulinArray(with: insulinObjects)
  9. }
  10. }
  11. private func fetchInsulin() async -> [NSManagedObjectID] {
  12. let results = await CoreDataStack.shared.fetchEntitiesAsync(
  13. ofType: PumpEventStored.self,
  14. onContext: pumpHistoryFetchContext,
  15. predicate: NSPredicate.pumpHistoryLast24h,
  16. key: "timestamp",
  17. ascending: true
  18. )
  19. return await pumpHistoryFetchContext.perform {
  20. guard let pumpEvents = results as? [PumpEventStored] else {
  21. return []
  22. }
  23. return pumpEvents.map(\.objectID)
  24. }
  25. }
  26. @MainActor private func updateInsulinArray(with insulinObjects: [PumpEventStored]) {
  27. insulinFromPersistence = insulinObjects
  28. manualTempBasal = apsManager.isManualTempBasal
  29. tempBasals = insulinFromPersistence.filter({ $0.tempBasal != nil })
  30. suspensions = insulinFromPersistence.filter {
  31. $0.type == EventType.pumpSuspend.rawValue || $0.type == EventType.pumpResume.rawValue
  32. }
  33. let lastSuspension = suspensions.last
  34. pumpSuspended = tempBasals.last?.timestamp ?? Date() > lastSuspension?.timestamp ?? .distantPast && lastSuspension?
  35. .type == EventType.pumpSuspend.rawValue
  36. }
  37. // Setup Last Bolus to display the bolus progress bar
  38. // The predicate filters out all external boluses to prevent the progress bar from displaying the amount of an external bolus when an external bolus is added after a pump bolus
  39. func setupLastBolus() {
  40. Task {
  41. guard let id = await self.fetchLastBolus() else { return }
  42. await updateLastBolus(with: id)
  43. }
  44. }
  45. func fetchLastBolus() async -> NSManagedObjectID? {
  46. let results = await CoreDataStack.shared.fetchEntitiesAsync(
  47. ofType: PumpEventStored.self,
  48. onContext: pumpHistoryFetchContext,
  49. predicate: NSPredicate.lastPumpBolus,
  50. key: "timestamp",
  51. ascending: false,
  52. fetchLimit: 1
  53. )
  54. return await pumpHistoryFetchContext.perform {
  55. guard let fetchedResults = results as? [PumpEventStored] else { return [].first }
  56. return fetchedResults.map(\.objectID).first
  57. }
  58. }
  59. @MainActor private func updateLastBolus(with ID: NSManagedObjectID) {
  60. do {
  61. lastPumpBolus = try viewContext.existingObject(with: ID) as? PumpEventStored
  62. } catch {
  63. debugPrint(
  64. "Home State: \(#function) \(DebuggingIdentifiers.failed) error while updating the insulin array: \(error.localizedDescription)"
  65. )
  66. }
  67. }
  68. }