EditTempTargetForm.swift 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406
  1. import Foundation
  2. import SwiftUI
  3. struct EditTempTargetForm: View {
  4. @ObservedObject var tempTarget: TempTargetStored
  5. @Environment(\.presentationMode) var presentationMode
  6. @Environment(\.colorScheme) var colorScheme
  7. @StateObject var state: OverrideConfig.StateModel
  8. @State private var displayPickerDuration: Bool = false
  9. @State private var displayPickerTarget: Bool = false
  10. @State private var tempTargetSensitivityAdjustmentType: TempTargetSensitivityAdjustmentType = .standard
  11. @State private var durationHours = 0
  12. @State private var durationMinutes = 0
  13. @State private var targetStep: Decimal = 5
  14. @State private var name: String
  15. @State private var target: Decimal
  16. @State private var duration: Decimal
  17. @State private var date: Date
  18. @State private var halfBasalTarget: Decimal
  19. @State private var percentage: Decimal
  20. @State private var hasChanges = false
  21. @State private var showAlert = false
  22. @State private var isUsingSlider = false
  23. @State private var isPreset = false
  24. @State private var isEnabled = false
  25. init(tempTargetToEdit: TempTargetStored, state: OverrideConfig.StateModel) {
  26. tempTarget = tempTargetToEdit
  27. _state = StateObject(wrappedValue: state)
  28. _name = State(initialValue: tempTargetToEdit.name ?? "")
  29. _target = State(initialValue: tempTargetToEdit.target?.decimalValue ?? 0)
  30. _duration = State(initialValue: tempTargetToEdit.duration?.decimalValue ?? 0)
  31. _date = State(initialValue: tempTargetToEdit.date ?? Date())
  32. _halfBasalTarget = State(initialValue: tempTargetToEdit.halfBasalTarget?.decimalValue ?? 160)
  33. _isPreset = State(initialValue: tempTargetToEdit.isPreset)
  34. _isEnabled = State(initialValue: tempTargetToEdit.enabled)
  35. if let hbt = tempTargetToEdit.halfBasalTarget?.decimalValue {
  36. let H = hbt
  37. let T = tempTargetToEdit.target?.decimalValue ?? 100
  38. let calcPercentage = Double(state.computeAdjustedPercentage(usingHBT: H, usingTarget: T) * 100)
  39. _percentage = State(initialValue: Decimal(calcPercentage))
  40. } else { _percentage = State(initialValue: Decimal(100)) }
  41. }
  42. var color: LinearGradient {
  43. colorScheme == .dark ? LinearGradient(
  44. gradient: Gradient(colors: [
  45. Color.bgDarkBlue,
  46. Color.bgDarkerDarkBlue
  47. ]),
  48. startPoint: .top,
  49. endPoint: .bottom
  50. ) :
  51. LinearGradient(
  52. gradient: Gradient(colors: [Color.gray.opacity(0.1)]),
  53. startPoint: .top,
  54. endPoint: .bottom
  55. )
  56. }
  57. private var formatter: NumberFormatter {
  58. let formatter = NumberFormatter()
  59. formatter.numberStyle = .decimal
  60. formatter.maximumFractionDigits = 0
  61. return formatter
  62. }
  63. private var glucoseFormatter: NumberFormatter {
  64. let formatter = NumberFormatter()
  65. formatter.numberStyle = .decimal
  66. if state.units == .mmolL {
  67. formatter.maximumFractionDigits = 1
  68. } else {
  69. formatter.maximumFractionDigits = 0
  70. }
  71. formatter.roundingMode = .halfUp
  72. return formatter
  73. }
  74. var body: some View {
  75. NavigationView {
  76. List {
  77. editTempTarget()
  78. saveButton
  79. }
  80. .listSectionSpacing(10)
  81. .listRowSpacing(10)
  82. .padding(.top, 30)
  83. .ignoresSafeArea(edges: .top)
  84. .scrollContentBackground(.hidden).background(color)
  85. .navigationTitle("Edit Temp Target")
  86. .navigationBarTitleDisplayMode(.inline)
  87. .toolbar {
  88. ToolbarItem(placement: .topBarLeading) {
  89. Button(action: {
  90. presentationMode.wrappedValue.dismiss()
  91. }, label: {
  92. Text("Cancel")
  93. })
  94. }
  95. }
  96. .onAppear {
  97. if halfBasalTarget != state.settingHalfBasalTarget { tempTargetSensitivityAdjustmentType = .slider }
  98. }
  99. }
  100. }
  101. @ViewBuilder private func editTempTarget() -> some View {
  102. Group {
  103. Section {
  104. HStack {
  105. Text("Name")
  106. Spacer()
  107. TextField("(Optional)", text: $name)
  108. .multilineTextAlignment(.trailing)
  109. .onChange(of: name) {
  110. hasChanges = true
  111. }
  112. }
  113. }.listRowBackground(Color.chart)
  114. Section {
  115. DatePicker("Date", selection: $date)
  116. .onChange(of: date) { hasChanges = true }
  117. }.listRowBackground(Color.chart)
  118. Section {
  119. VStack {
  120. HStack {
  121. Text("Duration")
  122. Spacer()
  123. Text(formatHrMin(Int(duration)))
  124. .foregroundColor(!displayPickerDuration ? .primary : .accentColor)
  125. }
  126. .onTapGesture {
  127. displayPickerDuration = toggleScrollWheel(displayPickerDuration)
  128. }
  129. .onChange(of: duration) { hasChanges = true }
  130. if displayPickerDuration {
  131. HStack {
  132. Picker(
  133. selection: Binding(
  134. get: {
  135. Int(truncating: duration as NSNumber) / 60
  136. },
  137. set: {
  138. let minutes = Int(truncating: duration as NSNumber) % 60
  139. let totalMinutes = $0 * 60 + minutes
  140. duration = Decimal(totalMinutes)
  141. hasChanges = true
  142. }
  143. ),
  144. label: Text("")
  145. ) {
  146. ForEach(0 ..< 24) { hour in
  147. Text("\(hour) hr").tag(hour)
  148. }
  149. }
  150. .pickerStyle(WheelPickerStyle())
  151. .frame(maxWidth: .infinity)
  152. Picker(
  153. selection: Binding(
  154. get: {
  155. Int(truncating: duration as NSNumber) %
  156. 60 // Convert Decimal to Int for modulus operation
  157. },
  158. set: {
  159. duration = Decimal((Int(truncating: duration as NSNumber) / 60) * 60 + $0)
  160. hasChanges = true
  161. }
  162. ),
  163. label: Text("")
  164. ) {
  165. ForEach(Array(stride(from: 0, through: 55, by: 5)), id: \.self) { minute in
  166. Text("\(minute) min").tag(minute)
  167. }
  168. }
  169. .pickerStyle(WheelPickerStyle())
  170. .frame(maxWidth: .infinity)
  171. }
  172. .listRowSeparator(.hidden, edges: .top)
  173. }
  174. }
  175. }.listRowBackground(Color.chart)
  176. Section {
  177. HStack {
  178. // Picker on the right side
  179. let settingsProvider = PickerSettingsProvider.shared
  180. let glucoseSetting = PickerSetting(value: 0, step: targetStep, min: 80, max: 270, type: .glucose)
  181. TargetPicker(
  182. label: "Target Glucose",
  183. selection: Binding(
  184. get: { target },
  185. set: { target = $0 }
  186. ),
  187. options: settingsProvider.generatePickerValues(
  188. from: glucoseSetting,
  189. units: state.units,
  190. roundMinToStep: true
  191. ),
  192. units: state.units,
  193. hasChanges: $hasChanges,
  194. targetStep: $targetStep,
  195. displayPickerTarget: $displayPickerTarget,
  196. toggleScrollWheel: toggleScrollWheel
  197. )
  198. }
  199. .onChange(of: target) {
  200. percentage = state.computeAdjustedPercentage(usingHBT: halfBasalTarget, usingTarget: target) * 100
  201. }
  202. }
  203. .listRowBackground(Color.chart)
  204. if target != state.normalTarget {
  205. let computedHalfBasalTarget = Decimal(
  206. state
  207. .computeHalfBasalTarget(usingTarget: target, usingPercentage: Double(percentage))
  208. )
  209. let sensHint = target > state.normalTarget ?
  210. "Reducing all delivered insulin to \(formattedPercentage(Double(percentage)))%." :
  211. "Increasing all delivered insulin by \(formattedPercentage(Double(percentage) - 100))%."
  212. if state.computeSliderLow(usingTarget: target) < state.computeSliderHigh(usingTarget: target) {
  213. Section(
  214. header: Text(sensHint)
  215. .textCase(.none)
  216. .foregroundStyle(colorScheme == .dark ? Color.orange : Color.accentColor),
  217. content: {
  218. VStack {
  219. Picker("Sensitivity Adjustment", selection: $tempTargetSensitivityAdjustmentType) {
  220. ForEach(TempTargetSensitivityAdjustmentType.allCases, id: \.self) { option in
  221. Text(option.rawValue).tag(option)
  222. }
  223. .pickerStyle(MenuPickerStyle())
  224. .onChange(of: tempTargetSensitivityAdjustmentType) { newValue in
  225. if newValue == .standard {
  226. halfBasalTarget = state.settingHalfBasalTarget
  227. percentage = (
  228. state
  229. .computeAdjustedPercentage(usingHBT: halfBasalTarget, usingTarget: target) *
  230. 100
  231. )
  232. }
  233. }
  234. }
  235. if tempTargetSensitivityAdjustmentType == .slider {
  236. Text("\(formattedPercentage(Double(percentage))) % Insulin")
  237. .foregroundColor(isUsingSlider ? .orange : Color.tabBar)
  238. .font(.title3)
  239. .fontWeight(.bold)
  240. Slider(
  241. value: Binding(
  242. get: {
  243. Double(truncating: percentage as NSNumber)
  244. },
  245. set: { newValue in
  246. percentage = Decimal(newValue)
  247. hasChanges = true
  248. halfBasalTarget = Decimal(state.computeHalfBasalTarget(
  249. usingTarget: target,
  250. usingPercentage: Double(percentage)
  251. ))
  252. }
  253. ),
  254. in: Double(state.computeSliderLow(usingTarget: target)) ...
  255. Double(state.computeSliderHigh(usingTarget: target)),
  256. step: 5
  257. ) {}
  258. minimumValueLabel: {
  259. Text("\(state.computeSliderLow(usingTarget: target), specifier: "%.0f")%")
  260. }
  261. maximumValueLabel: {
  262. Text("\(state.computeSliderHigh(usingTarget: target), specifier: "%.0f")%")
  263. }
  264. Divider()
  265. HStack {
  266. Text(
  267. "Half Basal Exercise Target:"
  268. )
  269. Spacer()
  270. Text(formattedGlucose(glucose: computedHalfBasalTarget))
  271. }.foregroundStyle(.primary)
  272. }
  273. }.padding(.vertical, 10)
  274. }
  275. )
  276. .listRowBackground(Color.chart)
  277. .padding(.top, -10)
  278. }
  279. }
  280. }
  281. }
  282. private var saveButton: some View {
  283. HStack {
  284. Spacer()
  285. Button(action: {
  286. if !state.isInputInvalid(target: target) {
  287. saveChanges()
  288. do {
  289. guard let moc = tempTarget.managedObjectContext else { return }
  290. guard moc.hasChanges else { return }
  291. try moc.save()
  292. if let currentActiveTempTarget = state.currentActiveTempTarget {
  293. Task {
  294. // TODO: - Creating a Run entry is probably needed for Overrides as well and the reason for "jumping" Overrides?
  295. // Disable previous active Temp Targets
  296. await state.disableAllActiveOverrides(
  297. except: currentActiveTempTarget.objectID,
  298. createOverrideRunEntry: false
  299. )
  300. // If the temp target which currently gets edited is enabled, then store it to the Temp Target JSON so that oref uses it
  301. if isEnabled {
  302. let tempTarget = TempTarget(
  303. name: name,
  304. createdAt: Date(),
  305. targetTop: target,
  306. targetBottom: target,
  307. duration: duration,
  308. enteredBy: TempTarget.manual,
  309. reason: TempTarget.custom,
  310. isPreset: isPreset ? true : false,
  311. enabled: isEnabled ? true : false,
  312. halfBasalTarget: halfBasalTarget
  313. )
  314. // Store to TempTargetStorage so that oref uses the edited Temp target
  315. state.saveTempTargetToStorage(tempTargets: [tempTarget])
  316. }
  317. // Update view
  318. state.updateLatestTempTargetConfiguration()
  319. }
  320. }
  321. hasChanges = false
  322. presentationMode.wrappedValue.dismiss()
  323. } catch {
  324. debugPrint("Failed to Edit Temp Target")
  325. }
  326. }
  327. }, label: {
  328. Text("Save")
  329. })
  330. .disabled(!hasChanges)
  331. .frame(maxWidth: .infinity, alignment: .center)
  332. .tint(.white)
  333. Spacer()
  334. }.listRowBackground(hasChanges ? Color(.systemBlue) : Color(.systemGray4))
  335. }
  336. private func saveChanges() {
  337. tempTarget.name = name
  338. tempTarget.target = NSDecimalNumber(decimal: target)
  339. tempTarget.duration = NSDecimalNumber(decimal: duration)
  340. tempTarget.date = date
  341. tempTarget.isUploadedToNS = false
  342. tempTarget.halfBasalTarget = NSDecimalNumber(decimal: halfBasalTarget)
  343. }
  344. private func toggleScrollWheel(_ toggle: Bool) -> Bool {
  345. displayPickerDuration = false
  346. displayPickerTarget = false
  347. return !toggle
  348. }
  349. private func resetValues() {
  350. name = tempTarget.name ?? ""
  351. target = tempTarget.target?.decimalValue ?? 0
  352. duration = tempTarget.duration?.decimalValue ?? 0
  353. date = tempTarget.date ?? Date()
  354. }
  355. private func totalDurationInMinutes() -> Int {
  356. let durationTotal = (durationHours * 60) + durationMinutes
  357. return max(0, durationTotal)
  358. }
  359. private func formattedPercentage(_ value: Double) -> String {
  360. let percentageNumber = NSNumber(value: value)
  361. return formatter.string(from: percentageNumber) ?? "\(value)"
  362. }
  363. private func formattedGlucose(glucose: Decimal) -> String {
  364. let formattedValue: String
  365. if state.units == .mgdL {
  366. formattedValue = glucoseFormatter.string(from: glucose as NSDecimalNumber) ?? "\(glucose)"
  367. } else {
  368. formattedValue = glucose.formattedAsMmolL
  369. }
  370. return "\(formattedValue) \(state.units.rawValue)"
  371. }
  372. }