EditTempTargetForm.swift 19 KB

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