AddTempTargetRootView.swift 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226
  1. import CoreData
  2. import SwiftUI
  3. import Swinject
  4. extension AddTempTarget {
  5. struct RootView: BaseView {
  6. let resolver: Resolver
  7. @StateObject var state = StateModel()
  8. @State private var isPromtPresented = false
  9. @State private var isRemoveAlertPresented = false
  10. @State private var removeAlert: Alert?
  11. @State private var isEditing = false
  12. @FetchRequest(
  13. entity: ViewPercentage.entity(),
  14. sortDescriptors: [NSSortDescriptor(key: "enabled", ascending: false)]
  15. ) var isEnabledArray: FetchedResults<ViewPercentage>
  16. @Environment(\.managedObjectContext) var moc
  17. private var formatter: NumberFormatter {
  18. let formatter = NumberFormatter()
  19. formatter.numberStyle = .decimal
  20. formatter.maximumFractionDigits = 1
  21. return formatter
  22. }
  23. var body: some View {
  24. Form {
  25. if !state.presets.isEmpty {
  26. Section(header: Text("Presets")) {
  27. ForEach(state.presets) { preset in
  28. presetView(for: preset)
  29. }
  30. }
  31. }
  32. Toggle(isOn: $state.viewPercantage) {
  33. Text("Exercise / Pre Meal Slider")
  34. }
  35. if state.viewPercantage {
  36. Section(
  37. header: Text("TT Effect on Basal and Sensitivity"),
  38. footer: Text(
  39. NSLocalizedString(
  40. "'Half Basal Target' (HBT) setting adjusts how a temp target affects basal and ISF.\n A lower HBT will allow Basal to be reduced earlier (at a less high TT).\n",
  41. comment: ""
  42. ) +
  43. NSLocalizedString(" HBT setting: ", comment: "") + "\(state.halfBasal) " +
  44. NSLocalizedString("mg/dl. Autosens.max setting determines the max endpoint", comment: "") +
  45. " (\(state.maxValue): \(state.maxValue * 100) %)"
  46. )
  47. ) {
  48. VStack {
  49. Slider(
  50. value: $state.percentage,
  51. in: 15 ...
  52. Double(state.maxValue * 100),
  53. step: 1,
  54. onEditingChanged: { editing in
  55. isEditing = editing
  56. }
  57. )
  58. Text("\(state.percentage.formatted(.number)) %")
  59. .foregroundColor(isEditing ? .orange : .blue)
  60. .font(.largeTitle)
  61. Divider()
  62. Text(
  63. NSLocalizedString("Temp Target to Save", comment: "") +
  64. (
  65. state
  66. .units == .mmolL ?
  67. ": \(computeTarget().asMmolL.formatted(.number.grouping(.never).rounded().precision(.fractionLength(1)))) mmol/L" :
  68. ": \(computeTarget().formatted(.number.grouping(.never).rounded().precision(.fractionLength(0)))) mg/dl"
  69. )
  70. ).foregroundColor(.primary).italic()
  71. }
  72. }
  73. } else {
  74. Section(header: Text("Custom")) {
  75. HStack {
  76. Text("Target")
  77. Spacer()
  78. DecimalTextField("0", value: $state.low, formatter: formatter, cleanInput: true)
  79. Text(state.units.rawValue).foregroundColor(.secondary)
  80. }
  81. HStack {
  82. Text("Duration")
  83. Spacer()
  84. DecimalTextField("0", value: $state.duration, formatter: formatter, cleanInput: true)
  85. Text("minutes").foregroundColor(.secondary)
  86. }
  87. DatePicker("Date", selection: $state.date)
  88. Button { isPromtPresented = true }
  89. label: { Text("Save as preset") }
  90. }
  91. }
  92. if state.viewPercantage {
  93. Section {
  94. HStack {
  95. Text("Duration")
  96. Spacer()
  97. DecimalTextField("0", value: $state.duration, formatter: formatter, cleanInput: true)
  98. Text("minutes").foregroundColor(.secondary)
  99. }
  100. DatePicker("Date", selection: $state.date)
  101. Button { isPromtPresented = true }
  102. label: { Text("Save as preset") }
  103. }
  104. }
  105. Section {
  106. Button { state.enact() }
  107. label: { Text("Enact") }
  108. Button { state.cancel() }
  109. label: { Text("Cancel Temp Target") }
  110. }
  111. }
  112. .popover(isPresented: $isPromtPresented) {
  113. Form {
  114. Section(header: Text("Enter preset name")) {
  115. TextField("Name", text: $state.newPresetName)
  116. Button {
  117. state.save()
  118. isPromtPresented = false
  119. }
  120. label: { Text("Save") }
  121. Button { isPromtPresented = false }
  122. label: { Text("Cancel") }
  123. }
  124. }
  125. }
  126. .onAppear(perform: configureView)
  127. .navigationTitle("Enact Temp Target")
  128. .navigationBarTitleDisplayMode(.automatic)
  129. .navigationBarItems(leading: Button("Close", action: state.hideModal))
  130. .onDisappear {
  131. if state.viewPercantage {
  132. let isEnabledMoc = ViewPercentage(context: moc)
  133. isEnabledMoc.enabled = true
  134. isEnabledMoc.date = Date()
  135. try? moc.save()
  136. } else {
  137. let isEnabledMoc = ViewPercentage(context: moc)
  138. isEnabledMoc.enabled = false
  139. isEnabledMoc.date = Date()
  140. try? moc.save()
  141. }
  142. }
  143. }
  144. func computeTarget() -> Decimal {
  145. var ratio = Decimal(state.percentage / 100)
  146. let hB = state.halfBasal
  147. let c = hB - 100
  148. var target = (c / ratio) - c + 100
  149. if c * (c + target - 100) <= 0 {
  150. ratio = state.maxValue
  151. target = (c / ratio) - c + 100
  152. }
  153. return target
  154. }
  155. private func presetView(for preset: TempTarget) -> some View {
  156. var low = preset.targetBottom
  157. var high = preset.targetTop
  158. if state.units == .mmolL {
  159. low = low?.asMmolL
  160. high = high?.asMmolL
  161. }
  162. return HStack {
  163. VStack {
  164. HStack {
  165. Text(preset.displayName)
  166. Spacer()
  167. }
  168. HStack(spacing: 2) {
  169. Text(
  170. "\(formatter.string(from: (low ?? 0) as NSNumber)!) - \(formatter.string(from: (high ?? 0) as NSNumber)!)"
  171. )
  172. .foregroundColor(.secondary)
  173. .font(.caption)
  174. Text(state.units.rawValue)
  175. .foregroundColor(.secondary)
  176. .font(.caption)
  177. Text("for")
  178. .foregroundColor(.secondary)
  179. .font(.caption)
  180. Text("\(formatter.string(from: preset.duration as NSNumber)!)")
  181. .foregroundColor(.secondary)
  182. .font(.caption)
  183. Text("min")
  184. .foregroundColor(.secondary)
  185. .font(.caption)
  186. Spacer()
  187. }.padding(.top, 2)
  188. }
  189. .contentShape(Rectangle())
  190. .onTapGesture {
  191. state.enactPreset(id: preset.id)
  192. }
  193. Image(systemName: "xmark.circle").foregroundColor(.secondary)
  194. .contentShape(Rectangle())
  195. .padding(.vertical)
  196. .onTapGesture {
  197. removeAlert = Alert(
  198. title: Text("Are you sure?"),
  199. message: Text("Delete preset \"\(preset.displayName)\""),
  200. primaryButton: .destructive(Text("Delete"), action: { state.removePreset(id: preset.id) }),
  201. secondaryButton: .cancel()
  202. )
  203. isRemoveAlertPresented = true
  204. }
  205. .alert(isPresented: $isRemoveAlertPresented) {
  206. removeAlert!
  207. }
  208. }
  209. }
  210. }
  211. }