UnitsLimitsSettingsStateModel.swift 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  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. } didSet: { [weak self] _ in
  18. self?.provider.migrateUnits()
  19. }
  20. maxIOB = settings.preferences.maxIOB
  21. maxCOB = settings.preferences.maxCOB
  22. }
  23. var isSettingUnchanged: Bool {
  24. preferences.maxIOB == maxIOB &&
  25. preferences.maxCOB == maxCOB
  26. }
  27. func saveIfChanged() {
  28. if !isSettingUnchanged {
  29. var newSettings = storage.retrieve(OpenAPS.Settings.preferences, as: Preferences.self) ?? Preferences()
  30. newSettings.maxIOB = maxIOB
  31. newSettings.maxCOB = maxCOB
  32. newSettings.timestamp = Date()
  33. storage.save(newSettings, as: OpenAPS.Settings.preferences)
  34. }
  35. }
  36. }
  37. }