CalibrationsStateModel.swift 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  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 = .mmolL
  14. override func subscribe() {
  15. units = settingsManager.settings.units
  16. calibrate = calibrationService.calibrate
  17. setupCalibrations()
  18. }
  19. private func setupCalibrations() {
  20. slope = calibrationService.slope
  21. intercept = calibrationService.intercept
  22. calibrations = calibrationService.calibrations
  23. items = calibrations.map {
  24. Item(calibration: $0)
  25. }
  26. }
  27. func addCalibration() {
  28. defer {
  29. UIApplication.shared.endEditing()
  30. setupCalibrations()
  31. }
  32. var glucose = newCalibration
  33. if units == .mmolL {
  34. glucose = newCalibration.asMgdL
  35. }
  36. guard let lastGlucose = glucoseStorage.recent().last,
  37. lastGlucose.dateString.addingTimeInterval(60 * 4.5) > Date(),
  38. let unfiltered = lastGlucose.unfiltered
  39. else {
  40. info(.service, "Glucose is stale for calibration")
  41. return
  42. }
  43. let calibration = Calibration(x: Double(unfiltered), y: Double(glucose))
  44. calibrationService.addCalibration(calibration)
  45. }
  46. func removeLast() {
  47. calibrationService.removeLast()
  48. setupCalibrations()
  49. }
  50. func removeAll() {
  51. calibrationService.removeAllCalibrations()
  52. setupCalibrations()
  53. }
  54. func removeAtIndex(_ index: Int) {
  55. let calibration = calibrations[index]
  56. calibrationService.removeCalibration(calibration)
  57. setupCalibrations()
  58. }
  59. }
  60. }