AddTempTargetRootView.swift 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239
  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: "date", 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. HStack {
  34. Text("Use Slider for")
  35. Image(systemName: "figure.highintensity.intervaltraining")
  36. Text("or")
  37. Image(systemName: "fork.knife")
  38. }
  39. }
  40. if state.viewPercantage {
  41. Section(
  42. header: Text("Percent Insulin")
  43. ) {
  44. VStack {
  45. Slider(
  46. value: $state.percentage,
  47. in: 15 ...
  48. Double(state.maxValue * 100),
  49. step: 1,
  50. onEditingChanged: { editing in
  51. isEditing = editing
  52. }
  53. )
  54. Text("\(state.percentage.formatted(.number)) %")
  55. .foregroundColor(isEditing ? .orange : .blue)
  56. .font(.largeTitle)
  57. Divider()
  58. Text(
  59. NSLocalizedString("Target glucose", comment: "") +
  60. (
  61. state
  62. .units == .mmolL ?
  63. ": \(computeTarget().asMmolL.formatted(.number.grouping(.never).rounded().precision(.fractionLength(1)))) mmol/L" :
  64. ": \(computeTarget().formatted(.number.grouping(.never).rounded().precision(.fractionLength(0)))) mg/dl"
  65. )
  66. ) // .foregroundColor(.primary).italic()
  67. Slider(
  68. value: $state.hbt,
  69. in: 104 ... 180,
  70. step: 1
  71. )
  72. Text(
  73. state
  74. .units == .mgdL ? "Half normal Basal at: \(state.hbt.formatted(.number)) mg/dl" :
  75. "Half normal Basal at: \(state.hbt.asMmolL.formatted(.number.grouping(.never).rounded().precision(.fractionLength(1)))) mmol/L"
  76. )
  77. .foregroundColor(.green)
  78. .font(.caption).italic()
  79. }
  80. }
  81. } else {
  82. Section(header: Text("Custom")) {
  83. HStack {
  84. Text("Target")
  85. Spacer()
  86. DecimalTextField("0", value: $state.low, formatter: formatter, cleanInput: true)
  87. Text(state.units.rawValue).foregroundColor(.secondary)
  88. }
  89. HStack {
  90. Text("Duration")
  91. Spacer()
  92. DecimalTextField("0", value: $state.duration, formatter: formatter, cleanInput: true)
  93. Text("minutes").foregroundColor(.secondary)
  94. }
  95. DatePicker("Date", selection: $state.date)
  96. Button { isPromtPresented = true }
  97. label: { Text("Save as preset") }
  98. }
  99. }
  100. if state.viewPercantage {
  101. Section {
  102. HStack {
  103. Text("Duration")
  104. Spacer()
  105. DecimalTextField("0", value: $state.duration, formatter: formatter, cleanInput: true)
  106. Text("minutes").foregroundColor(.secondary)
  107. }
  108. DatePicker("Date", selection: $state.date)
  109. Button { isPromtPresented = true }
  110. label: { Text("Save as preset") }
  111. }
  112. }
  113. Section {
  114. Button { state.enact() }
  115. label: { Text("Enact") }
  116. Button { state.cancel() }
  117. label: { Text("Cancel Temp Target") }
  118. }
  119. }
  120. .popover(isPresented: $isPromtPresented) {
  121. Form {
  122. Section(header: Text("Enter preset name")) {
  123. TextField("Name", text: $state.newPresetName)
  124. Button {
  125. state.save()
  126. isPromtPresented = false
  127. }
  128. label: { Text("Save") }
  129. Button { isPromtPresented = false }
  130. label: { Text("Cancel") }
  131. }
  132. }
  133. }
  134. .onAppear {
  135. configureView()
  136. state.hbt = isEnabledArray.first?.hbt ?? 160
  137. }
  138. .navigationTitle("Enact Temp Target")
  139. .navigationBarTitleDisplayMode(.automatic)
  140. .navigationBarItems(leading: Button("Close", action: state.hideModal))
  141. .onDisappear {
  142. if state.viewPercantage, state.saveSettings {
  143. let isEnabledMoc = ViewPercentage(context: moc)
  144. isEnabledMoc.enabled = true
  145. isEnabledMoc.date = Date()
  146. isEnabledMoc.hbt = state.hbt
  147. try? moc.save()
  148. } else {
  149. let isEnabledMoc = ViewPercentage(context: moc)
  150. isEnabledMoc.enabled = false
  151. isEnabledMoc.date = Date()
  152. isEnabledMoc.hbt = isEnabledArray.first?.hbt ?? 160
  153. try? moc.save()
  154. }
  155. }
  156. }
  157. func computeTarget() -> Decimal {
  158. var ratio = Decimal(state.percentage / 100)
  159. let c = Decimal(state.hbt - 100)
  160. var target = (c / ratio) - c + 100
  161. if c * (c + target - 100) <= 0 {
  162. ratio = state.maxValue
  163. target = (c / ratio) - c + 100
  164. }
  165. return target
  166. }
  167. private func presetView(for preset: TempTarget) -> some View {
  168. var low = preset.targetBottom
  169. var high = preset.targetTop
  170. if state.units == .mmolL {
  171. low = low?.asMmolL
  172. high = high?.asMmolL
  173. }
  174. return HStack {
  175. VStack {
  176. HStack {
  177. Text(preset.displayName)
  178. Spacer()
  179. }
  180. HStack(spacing: 2) {
  181. Text(
  182. "\(formatter.string(from: (low ?? 0) as NSNumber)!) - \(formatter.string(from: (high ?? 0) as NSNumber)!)"
  183. )
  184. .foregroundColor(.secondary)
  185. .font(.caption)
  186. Text(state.units.rawValue)
  187. .foregroundColor(.secondary)
  188. .font(.caption)
  189. Text("for")
  190. .foregroundColor(.secondary)
  191. .font(.caption)
  192. Text("\(formatter.string(from: preset.duration as NSNumber)!)")
  193. .foregroundColor(.secondary)
  194. .font(.caption)
  195. Text("min")
  196. .foregroundColor(.secondary)
  197. .font(.caption)
  198. Spacer()
  199. }.padding(.top, 2)
  200. }
  201. .contentShape(Rectangle())
  202. .onTapGesture {
  203. state.enactPreset(id: preset.id)
  204. }
  205. Image(systemName: "xmark.circle").foregroundColor(.secondary)
  206. .contentShape(Rectangle())
  207. .padding(.vertical)
  208. .onTapGesture {
  209. removeAlert = Alert(
  210. title: Text("Are you sure?"),
  211. message: Text("Delete preset \"\(preset.displayName)\""),
  212. primaryButton: .destructive(Text("Delete"), action: { state.removePreset(id: preset.id) }),
  213. secondaryButton: .cancel()
  214. )
  215. isRemoveAlertPresented = true
  216. }
  217. .alert(isPresented: $isRemoveAlertPresented) {
  218. removeAlert!
  219. }
  220. }
  221. }
  222. }
  223. }