SuspendThresholdEditorViewModel.swift 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. //
  2. // SuspendThresholdEditorViewModel.swift
  3. // LoopKitUI
  4. //
  5. // Created by Nathaniel Hamming on 2021-03-01.
  6. // Copyright © 2021 LoopKit Authors. All rights reserved.
  7. //
  8. import Foundation
  9. import HealthKit
  10. import LoopKit
  11. struct SuspendThresholdEditorViewModel {
  12. let guardrail = Guardrail.suspendThreshold
  13. let suspendThreshold: HKQuantity?
  14. let suspendThresholdUnit: HKUnit
  15. let maxSuspendThresholdValue: HKQuantity
  16. var saveSuspendThreshold: (_ suspendThreshold: HKQuantity, _ displayGlucoseUnit: HKUnit) -> Void
  17. public init(therapySettingsViewModel: TherapySettingsViewModel,
  18. mode: SettingsPresentationMode,
  19. didSave: (() -> Void)? = nil)
  20. {
  21. self.suspendThreshold = therapySettingsViewModel.suspendThreshold?.quantity
  22. self.suspendThresholdUnit = therapySettingsViewModel.suspendThreshold?.unit ?? .milligramsPerDeciliter
  23. if mode == .acceptanceFlow {
  24. // During a review/acceptance flow, do not limit suspend threshold by other targets
  25. self.maxSuspendThresholdValue = Guardrail.suspendThreshold.absoluteBounds.upperBound
  26. } else {
  27. self.maxSuspendThresholdValue = Guardrail.maxSuspendThresholdValue(
  28. correctionRangeSchedule: therapySettingsViewModel.glucoseTargetRangeSchedule,
  29. preMealTargetRange: therapySettingsViewModel.correctionRangeOverrides.preMeal,
  30. workoutTargetRange: therapySettingsViewModel.correctionRangeOverrides.workout)
  31. }
  32. self.saveSuspendThreshold = { [weak therapySettingsViewModel] suspendThreshold, displayGlucoseUnit in
  33. guard let therapySettingsViewModel = therapySettingsViewModel else {
  34. return
  35. }
  36. therapySettingsViewModel.saveSuspendThreshold(quantity: suspendThreshold, withDisplayGlucoseUnit: displayGlucoseUnit)
  37. didSave?()
  38. }
  39. }
  40. }