CalibrationsStateModel.swift 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  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. @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. return
  41. }
  42. let calibration = Calibration(x: Double(unfiltered), y: Double(glucose))
  43. calibrationService.addCalibration(calibration)
  44. }
  45. func removeLast() {
  46. calibrationService.removeLast()
  47. setupCalibrations()
  48. }
  49. func removeAll() {
  50. calibrationService.removeAllCalibrations()
  51. setupCalibrations()
  52. }
  53. func removeAtIndex(_ index: Int) {
  54. let calibration = calibrations[index]
  55. calibrationService.removeCalibration(calibration)
  56. setupCalibrations()
  57. }
  58. }
  59. }