CalibrationsStateModel.swift 2.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. import SwiftDate
  2. import SwiftUI
  3. extension Calibrations {
  4. final class StateModel: BaseStateModel<Provider> {
  5. @Injected() var glucoseStorage: GlucoseStorage!
  6. @Injected() var calibrationService: CalibrationService!
  7. @Published var slope: Double = 1
  8. @Published var intercept: Double = 1
  9. @Published var newCalibration: Decimal = 0
  10. @Published var calibrations: [Calibration] = []
  11. @Published var calibrate: (Int) -> Double = { Double($0) }
  12. @Published var items: [Item] = []
  13. var units: GlucoseUnits = .mgdL
  14. // TODO: - test if we need to use the viewContext here
  15. private let context = CoreDataStack.shared.newTaskContext()
  16. override func subscribe() {
  17. units = settingsManager.settings.units
  18. calibrate = calibrationService.calibrate
  19. setupCalibrations()
  20. }
  21. private func setupCalibrations() {
  22. slope = calibrationService.slope
  23. intercept = calibrationService.intercept
  24. calibrations = calibrationService.calibrations
  25. items = calibrations.map {
  26. Item(calibration: $0)
  27. }
  28. }
  29. private func fetchAndProcessGlucose() -> GlucoseStored? {
  30. do {
  31. debugPrint("Calibrations State Model: \(#function) \(DebuggingIdentifiers.succeeded) fetched glucose")
  32. return try context.fetch(GlucoseStored.fetch(
  33. NSPredicate.predicateFor20MinAgo,
  34. ascending: false,
  35. fetchLimit: 1
  36. )).first
  37. } catch {
  38. debugPrint("Calibrations State Model: \(#function) \(DebuggingIdentifiers.failed) failed to fetch glucose")
  39. return nil
  40. }
  41. }
  42. func addCalibration() {
  43. defer {
  44. UIApplication.shared.endEditing()
  45. setupCalibrations()
  46. }
  47. var glucose = newCalibration
  48. if units == .mmolL {
  49. glucose = newCalibration.asMgdL
  50. }
  51. if let lastGlucose = fetchAndProcessGlucose() {
  52. let unfiltered = lastGlucose.glucose
  53. let calibration = Calibration(x: Double(unfiltered), y: Double(glucose))
  54. calibrationService.addCalibration(calibration)
  55. } else {
  56. info(.service, "Glucose is stale for calibration")
  57. return
  58. }
  59. }
  60. func removeLast() {
  61. calibrationService.removeLast()
  62. setupCalibrations()
  63. }
  64. func removeAll() {
  65. calibrationService.removeAllCalibrations()
  66. setupCalibrations()
  67. }
  68. func removeAtIndex(_ index: Int) {
  69. let calibration = calibrations[index]
  70. calibrationService.removeCalibration(calibration)
  71. setupCalibrations()
  72. }
  73. }
  74. }