TargetsEditorStateModel.swift 3.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. import SwiftUI
  2. extension TargetsEditor {
  3. final class StateModel: BaseStateModel<Provider> {
  4. @Injected() var settingsManager: SettingsManager!
  5. @Published var items: [Item] = []
  6. let timeValues = stride(from: 0.0, to: 1.days.timeInterval, by: 30.minutes.timeInterval).map { $0 }
  7. var rateValues: [Double] {
  8. switch units {
  9. case .mgdL:
  10. return stride(from: 72, to: 180.01, by: 1.0).map { $0 }
  11. case .mmolL:
  12. return stride(from: 4.0, to: 10.01, by: 0.1).map { $0 }
  13. }
  14. }
  15. var canAdd: Bool {
  16. guard let lastItem = items.last else { return true }
  17. return lastItem.timeIndex < timeValues.count - 1
  18. }
  19. private(set) var units: GlucoseUnits = .mmolL
  20. override func subscribe() {
  21. let profile = provider.profile
  22. units = profile.units
  23. items = profile.targets.map { value in
  24. let timeIndex = timeValues.firstIndex(of: Double(value.offset * 60)) ?? 0
  25. let lowIndex = rateValues.firstIndex(of: Double(value.low)) ?? 0
  26. let highIndex = rateValues.firstIndex(of: Double(value.high)) ?? 0
  27. return Item(lowIndex: lowIndex, highIndex: highIndex, timeIndex: timeIndex)
  28. }
  29. }
  30. func add() {
  31. var time = 0
  32. var low = 0
  33. var high = 0
  34. if let last = items.last {
  35. time = last.timeIndex + 1
  36. low = last.lowIndex
  37. high = last.highIndex
  38. }
  39. let newItem = Item(lowIndex: low, highIndex: high, timeIndex: time)
  40. items.append(newItem)
  41. }
  42. func save() {
  43. let targets = items.map { item -> BGTargetEntry in
  44. let fotmatter = DateFormatter()
  45. fotmatter.timeZone = TimeZone(secondsFromGMT: 0)
  46. fotmatter.dateFormat = "HH:mm:ss"
  47. let date = Date(timeIntervalSince1970: self.timeValues[item.timeIndex])
  48. let minutes = Int(date.timeIntervalSince1970 / 60)
  49. let low = Decimal(self.rateValues[item.lowIndex])
  50. let high = Decimal(self.rateValues[item.highIndex])
  51. return BGTargetEntry(low: low, high: high, start: fotmatter.string(from: date), offset: minutes)
  52. }
  53. let profile = BGTargets(units: units, userPrefferedUnits: settingsManager.settings.units, targets: targets)
  54. provider.saveProfile(profile)
  55. }
  56. func validate() {
  57. DispatchQueue.main.async {
  58. let uniq = Array(Set(self.items))
  59. let sorted = uniq.sorted { $0.timeIndex < $1.timeIndex }
  60. .map { item -> Item in
  61. guard item.highIndex < item.lowIndex else { return item }
  62. return Item(lowIndex: item.lowIndex, highIndex: item.lowIndex, timeIndex: item.timeIndex)
  63. }
  64. sorted.first?.timeIndex = 0
  65. self.items = sorted
  66. if self.items.isEmpty {
  67. self.units = self.settingsManager.settings.units
  68. }
  69. }
  70. }
  71. }
  72. }