CalibrationsStateModel.swift 1.8 KB

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