CalibrationsStateModel.swift 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  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. @Injected() var settingsManager: SettingsManager!
  8. @Published var slope: Double = 1
  9. @Published var intercept: Double = 1
  10. @Published var newCalibration: Decimal = 0
  11. @Published var calibrations: [Calibration] = []
  12. @Published var calibrate: (Double) -> Double = { $0 }
  13. var units: GlucoseUnits = .mmolL
  14. override func subscribe() {
  15. slope = calibrationService.slope
  16. intercept = calibrationService.intercept
  17. units = settingsManager.settings.units
  18. calibrations = calibrationService.calibrations
  19. calibrate = calibrationService.calibrate
  20. }
  21. func addCalibration() {
  22. defer {
  23. hideModal()
  24. }
  25. var glucose = newCalibration
  26. if units == .mmolL {
  27. glucose = newCalibration.asMgdL
  28. }
  29. guard let lastGlucose = glucoseStorage.recent().last,
  30. lastGlucose.dateString.addingTimeInterval(60 * 4.5) > Date(),
  31. let unfiltered = lastGlucose.unfiltered
  32. else {
  33. warning(.service, "Glucose is invalid for calibration")
  34. return
  35. }
  36. let calibration = Calibration(x: Double(unfiltered), y: Double(glucose))
  37. calibrationService.addCalibration(calibration)
  38. }
  39. func removeLast() {
  40. calibrationService.removeLast()
  41. hideModal()
  42. }
  43. func removeAll() {
  44. calibrationService.removeAllCalibrations()
  45. hideModal()
  46. }
  47. }
  48. }