TargetsEditorStateModel.swift 3.1 KB

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