UnitsLimitsSettingsStateModel.swift 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. import SwiftUI
  2. extension UnitsLimitsSettings {
  3. final class StateModel: BaseStateModel<Provider> {
  4. @Injected() var settings: SettingsManager!
  5. @Injected() var storage: FileStorage!
  6. @Published var units: GlucoseUnits = .mgdL
  7. @Published var unitsIndex = 0 // 0 = mg/dl
  8. @Published var maxIOB: Decimal = 0
  9. @Published var maxCOB: Decimal = 120
  10. var preferences: Preferences {
  11. settingsManager.preferences
  12. }
  13. override func subscribe() {
  14. units = settingsManager.settings.units
  15. subscribeSetting(\.units, on: $unitsIndex.map { $0 == 0 ? GlucoseUnits.mgdL : .mmolL }) {
  16. unitsIndex = $0 == .mgdL ? 0 : 1
  17. }
  18. maxIOB = settings.preferences.maxIOB
  19. maxCOB = settings.preferences.maxCOB
  20. }
  21. var isSettingUnchanged: Bool {
  22. preferences.maxIOB == maxIOB &&
  23. preferences.maxCOB == maxCOB
  24. }
  25. func saveIfChanged() {
  26. if !isSettingUnchanged {
  27. var newSettings = storage.retrieve(OpenAPS.Settings.preferences, as: Preferences.self) ?? Preferences()
  28. newSettings.maxIOB = maxIOB
  29. newSettings.maxCOB = maxCOB
  30. newSettings.timestamp = Date()
  31. storage.save(newSettings, as: OpenAPS.Settings.preferences)
  32. }
  33. }
  34. }
  35. }
  36. extension UnitsLimitsSettings.StateModel: SettingsObserver {
  37. func settingsDidChange(_: FreeAPSSettings) {
  38. units = settingsManager.settings.units
  39. }
  40. }