EditOverrideForm.swift 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626
  1. import Foundation
  2. import SwiftUI
  3. struct EditOverrideForm: View {
  4. var override: OverrideStored
  5. @Environment(\.presentationMode) var presentationMode
  6. @Environment(\.colorScheme) var colorScheme
  7. @Environment(AppState.self) var appState
  8. @Bindable var state: Adjustments.StateModel
  9. @State private var name: String
  10. @State private var percentage: Double
  11. @State private var indefinite: Bool
  12. @State private var duration: Decimal
  13. @State private var target: Decimal?
  14. @State private var advancedSettings: Bool
  15. @State private var smbIsOff: Bool
  16. @State private var smbIsScheduledOff: Bool
  17. @State private var start: Decimal?
  18. @State private var end: Decimal?
  19. @State private var isfAndCr: Bool
  20. @State private var isf: Bool
  21. @State private var cr: Bool
  22. @State private var smbMinutes: Decimal?
  23. @State private var uamMinutes: Decimal?
  24. @State private var selectedIsfCrOption: IsfAndOrCrOptions
  25. @State private var selectedDisableSmbOption: DisableSmbOptions
  26. @State private var hasChanges = false
  27. @State private var isEditing = false
  28. @State private var target_override = false
  29. @State private var percentageStep: Int = 1
  30. @State private var displayPickerPercentage: Bool = false
  31. @State private var displayPickerDuration: Bool = false
  32. @State private var targetStep: Decimal = 1
  33. @State private var displayPickerTarget: Bool = false
  34. @State private var displayPickerDisableSmbSchedule: Bool = false
  35. @State private var displayPickerSmbMinutes: Bool = false
  36. init(overrideToEdit: OverrideStored, state: Adjustments.StateModel) {
  37. override = overrideToEdit
  38. _state = Bindable(wrappedValue: state)
  39. _name = State(initialValue: overrideToEdit.name ?? "")
  40. _percentage = State(initialValue: overrideToEdit.percentage)
  41. _indefinite = State(initialValue: overrideToEdit.indefinite)
  42. _duration = State(initialValue: overrideToEdit.duration?.decimalValue ?? 0)
  43. _target = State(initialValue: overrideToEdit.target?.decimalValue)
  44. _target_override = State(initialValue: overrideToEdit.target != nil && overrideToEdit.target?.decimalValue != 0)
  45. _advancedSettings = State(initialValue: overrideToEdit.advancedSettings)
  46. _smbIsOff = State(initialValue: overrideToEdit.smbIsOff)
  47. _smbIsScheduledOff = State(initialValue: overrideToEdit.smbIsScheduledOff)
  48. _start = State(initialValue: overrideToEdit.start?.decimalValue)
  49. _end = State(initialValue: overrideToEdit.end?.decimalValue)
  50. _isfAndCr = State(initialValue: overrideToEdit.isfAndCr)
  51. _isf = State(initialValue: overrideToEdit.isf)
  52. _cr = State(initialValue: overrideToEdit.cr)
  53. _selectedIsfCrOption = State(
  54. initialValue: overrideToEdit.isfAndCr ? .isfAndCr
  55. : (overrideToEdit.isf ? .isf : (overrideToEdit.cr ? .cr : .nothing))
  56. )
  57. _selectedDisableSmbOption = State(
  58. initialValue: overrideToEdit.smbIsScheduledOff ? .disableOnSchedule
  59. : (overrideToEdit.smbIsOff ? .disable : .dontDisable)
  60. )
  61. _smbMinutes = State(initialValue: overrideToEdit.smbMinutes?.decimalValue)
  62. _uamMinutes = State(initialValue: overrideToEdit.uamMinutes?.decimalValue)
  63. }
  64. private var percentageSelection: Binding<Double> {
  65. Binding<Double>(
  66. get: {
  67. let value = floor(percentage / Double(percentageStep)) * Double(percentageStep)
  68. return max(10, min(value, 200))
  69. },
  70. set: {
  71. percentage = $0
  72. hasChanges = true
  73. }
  74. )
  75. }
  76. var body: some View {
  77. NavigationView {
  78. List {
  79. editOverride()
  80. saveButton
  81. }
  82. .listSectionSpacing(10)
  83. .padding(.top, 30)
  84. .ignoresSafeArea(edges: .top)
  85. .scrollContentBackground(.hidden)
  86. .background(appState.trioBackgroundColor(for: colorScheme))
  87. .navigationTitle("Edit Override")
  88. .navigationBarTitleDisplayMode(.inline)
  89. .toolbar {
  90. ToolbarItem(placement: .topBarLeading) {
  91. Button(action: {
  92. presentationMode.wrappedValue.dismiss()
  93. }, label: {
  94. Text("Cancel")
  95. })
  96. }
  97. ToolbarItem(placement: .topBarTrailing) {
  98. Button(
  99. action: {
  100. state.isHelpSheetPresented.toggle()
  101. },
  102. label: {
  103. Image(systemName: "questionmark.circle")
  104. }
  105. )
  106. }
  107. }
  108. .onDisappear {
  109. if !hasChanges {
  110. // Reset UI changes
  111. resetValues()
  112. }
  113. }
  114. .sheet(isPresented: $state.isHelpSheetPresented) {
  115. OverrideHelpView(state: state, helpSheetDetent: $state.helpSheetDetent)
  116. }
  117. }
  118. }
  119. @ViewBuilder private func editOverride() -> some View {
  120. Group {
  121. if override.name != nil {
  122. Section {
  123. HStack {
  124. Text("Name")
  125. Spacer()
  126. TextField("Name", text: $name)
  127. .onChange(of: name) { hasChanges = true }
  128. .multilineTextAlignment(.trailing)
  129. }
  130. }
  131. .listRowBackground(Color.chart)
  132. }
  133. // Percentage Picker
  134. Section(footer: state.percentageDescription(percentage)) {
  135. HStack {
  136. Text("Basal Rate Adjustment")
  137. Spacer()
  138. Text("\(percentage.formatted(.number)) %")
  139. .foregroundColor(!displayPickerPercentage ? .primary : .accentColor)
  140. .onTapGesture {
  141. displayPickerPercentage = toggleScrollWheel(displayPickerPercentage)
  142. }
  143. }
  144. if displayPickerPercentage {
  145. HStack {
  146. // Radio buttons and text on the left side
  147. VStack(alignment: .leading) {
  148. // Radio buttons for step iteration
  149. ForEach([1, 5], id: \.self) { step in
  150. RadioButton(isSelected: percentageStep == step, label: "\(step) %") {
  151. percentageStep = step
  152. percentage = Adjustments.StateModel.roundOverridePercentageToStep(percentage, step)
  153. }
  154. .padding(.top, 10)
  155. }
  156. }
  157. .frame(maxWidth: .infinity)
  158. Spacer()
  159. // Picker on the right side
  160. Picker(
  161. selection: percentageSelection,
  162. label: Text("")
  163. ) {
  164. ForEach(
  165. Array(stride(from: 40.0, through: 150.0, by: Double(percentageStep))),
  166. id: \.self
  167. ) { percent in
  168. Text("\(Int(percent)) %").tag(percent)
  169. }
  170. }
  171. .pickerStyle(WheelPickerStyle())
  172. .frame(maxWidth: .infinity)
  173. }
  174. .listRowSeparator(.hidden, edges: .top)
  175. }
  176. // Picker for ISF/CR settings
  177. Picker("Also Change", selection: $selectedIsfCrOption) {
  178. ForEach(IsfAndOrCrOptions.allCases, id: \.self) { option in
  179. Text(option.rawValue).tag(option)
  180. }
  181. }
  182. .pickerStyle(MenuPickerStyle())
  183. .onChange(of: selectedIsfCrOption) { _, newValue in
  184. switch newValue {
  185. case .isfAndCr:
  186. isfAndCr = true
  187. isf = false
  188. cr = false
  189. case .isf:
  190. isfAndCr = false
  191. isf = true
  192. cr = false
  193. case .cr:
  194. isfAndCr = false
  195. isf = false
  196. cr = true
  197. case .nothing:
  198. isfAndCr = false
  199. isf = false
  200. cr = false
  201. }
  202. hasChanges = true
  203. }
  204. }
  205. .listRowBackground(Color.chart)
  206. Section {
  207. Toggle(isOn: $target_override) {
  208. Text("Override Target")
  209. }
  210. .onChange(of: target_override) {
  211. hasChanges = true
  212. }
  213. // Target Glucose Picker
  214. if target_override {
  215. let settingsProvider = PickerSettingsProvider.shared
  216. let glucoseSetting = PickerSetting(value: 0, step: targetStep, min: 72, max: 270, type: .glucose)
  217. TargetPicker(
  218. label: "Target Glucose",
  219. selection: Binding(
  220. get: { target ?? 100 },
  221. set: { target = $0 }
  222. ),
  223. options: settingsProvider.generatePickerValues(
  224. from: glucoseSetting,
  225. units: state.units,
  226. roundMinToStep: true
  227. ),
  228. units: state.units,
  229. hasChanges: $hasChanges,
  230. targetStep: $targetStep,
  231. displayPickerTarget: $displayPickerTarget,
  232. toggleScrollWheel: toggleScrollWheel
  233. )
  234. .onAppear {
  235. if target == 0 || target == nil {
  236. target = 100
  237. }
  238. }
  239. }
  240. }
  241. .listRowBackground(Color.chart)
  242. Section {
  243. // Picker for Disable SMB settings
  244. Picker("Disable SMBs", selection: $selectedDisableSmbOption) {
  245. ForEach(DisableSmbOptions.allCases, id: \.self) { option in
  246. Text(option.rawValue).tag(option)
  247. }
  248. }
  249. .pickerStyle(MenuPickerStyle())
  250. .onChange(of: selectedDisableSmbOption) { _, newValue in
  251. switch newValue {
  252. case .dontDisable:
  253. smbIsOff = false
  254. smbIsScheduledOff = false
  255. case .disable:
  256. smbIsOff = true
  257. smbIsScheduledOff = false
  258. case .disableOnSchedule:
  259. smbIsOff = false
  260. smbIsScheduledOff = true
  261. }
  262. hasChanges = true
  263. }
  264. if smbIsScheduledOff {
  265. // First Hour SMBs Are Disabled
  266. HStack {
  267. Text("From")
  268. Spacer()
  269. Text(
  270. state.is24HourFormat() ? state.format24Hour(Int(truncating: start! as NSNumber)) + ":00" :
  271. state.convertTo12HourFormat(Int(truncating: start! as NSNumber))
  272. )
  273. .foregroundColor(!displayPickerDisableSmbSchedule ? .primary : .accentColor)
  274. .onTapGesture {
  275. displayPickerDisableSmbSchedule = toggleScrollWheel(displayPickerDisableSmbSchedule)
  276. }
  277. Spacer()
  278. Divider().frame(width: 1, height: 20)
  279. Spacer()
  280. Text("To")
  281. Spacer()
  282. Text(
  283. state.is24HourFormat() ? state.format24Hour(Int(truncating: end! as NSNumber)) + ":00" :
  284. state.convertTo12HourFormat(Int(truncating: end! as NSNumber))
  285. )
  286. .foregroundColor(!displayPickerDisableSmbSchedule ? .primary : .accentColor)
  287. .onTapGesture {
  288. displayPickerDisableSmbSchedule = toggleScrollWheel(displayPickerDisableSmbSchedule)
  289. }
  290. }
  291. if displayPickerDisableSmbSchedule {
  292. HStack {
  293. Picker(selection: Binding(
  294. get: { Int(truncating: start! as NSNumber) },
  295. set: {
  296. start = Decimal($0)
  297. hasChanges = true
  298. }
  299. ), label: Text("")) {
  300. if state.is24HourFormat() {
  301. ForEach(0 ..< 24, id: \.self) { hour in
  302. Text(state.format24Hour(hour) + ":00").tag(hour)
  303. }
  304. } else {
  305. ForEach(0 ..< 24, id: \.self) { hour in
  306. Text(state.convertTo12HourFormat(hour)).tag(hour)
  307. }
  308. }
  309. }
  310. .pickerStyle(WheelPickerStyle())
  311. .frame(maxWidth: .infinity)
  312. Picker(selection: Binding(
  313. get: { Int(truncating: end! as NSNumber) },
  314. set: {
  315. end = Decimal($0)
  316. hasChanges = true
  317. }
  318. ), label: Text("")) {
  319. if state.is24HourFormat() {
  320. ForEach(0 ..< 24, id: \.self) { hour in
  321. Text(state.format24Hour(hour) + ":00").tag(hour)
  322. }
  323. } else {
  324. ForEach(0 ..< 24, id: \.self) { hour in
  325. Text(state.convertTo12HourFormat(hour)).tag(hour)
  326. }
  327. }
  328. }
  329. .pickerStyle(WheelPickerStyle())
  330. .frame(maxWidth: .infinity)
  331. }
  332. .listRowSeparator(.hidden, edges: .top)
  333. }
  334. }
  335. }
  336. .listRowBackground(Color.chart)
  337. if !smbIsOff {
  338. Section {
  339. Toggle(isOn: $advancedSettings) {
  340. Text("Change Max SMB Minutes")
  341. }
  342. .onChange(of: advancedSettings) { hasChanges = true }
  343. if advancedSettings {
  344. // SMB Minutes Picker
  345. HStack {
  346. Text("SMB")
  347. Spacer()
  348. Text("\(smbMinutes?.formatted(.number) ?? "\(state.defaultSmbMinutes)") min")
  349. .foregroundColor(!displayPickerSmbMinutes ? .primary : .accentColor)
  350. .onTapGesture {
  351. displayPickerSmbMinutes = toggleScrollWheel(displayPickerSmbMinutes)
  352. }
  353. Spacer()
  354. Divider().frame(width: 1, height: 20)
  355. Spacer()
  356. Text("UAM")
  357. Spacer()
  358. Text("\(uamMinutes?.formatted(.number) ?? "\(state.defaultUamMinutes)") min")
  359. .foregroundColor(!displayPickerSmbMinutes ? .primary : .accentColor)
  360. .onTapGesture {
  361. displayPickerSmbMinutes = toggleScrollWheel(displayPickerSmbMinutes)
  362. }
  363. }
  364. if displayPickerSmbMinutes {
  365. HStack {
  366. Picker(
  367. selection: Binding(
  368. get: { smbMinutes ?? state.defaultSmbMinutes },
  369. set: {
  370. smbMinutes = $0
  371. hasChanges = true
  372. }
  373. ),
  374. label: Text("")
  375. ) {
  376. ForEach(Array(stride(from: 0, through: 180, by: 5)), id: \.self) { minute in
  377. Text("\(minute) min").tag(Decimal(minute))
  378. }
  379. }
  380. .pickerStyle(WheelPickerStyle())
  381. .frame(maxWidth: .infinity)
  382. Picker(
  383. selection: Binding(
  384. get: { uamMinutes ?? state.defaultUamMinutes },
  385. set: {
  386. uamMinutes = $0
  387. hasChanges = true
  388. }
  389. ),
  390. label: Text("")
  391. ) {
  392. ForEach(Array(stride(from: 0, through: 180, by: 5)), id: \.self) { minute in
  393. Text("\(minute) min").tag(Decimal(minute))
  394. }
  395. }
  396. .pickerStyle(WheelPickerStyle())
  397. .frame(maxWidth: .infinity)
  398. }
  399. .listRowSeparator(.hidden, edges: .top)
  400. }
  401. }
  402. }
  403. .listRowBackground(Color.chart)
  404. }
  405. Section {
  406. Toggle(isOn: $indefinite) { Text("Enable Indefinitely") }
  407. .onChange(of: indefinite) { hasChanges = true }
  408. if !indefinite {
  409. HStack {
  410. Text("Duration")
  411. Spacer()
  412. Text(state.formatHrMin(Int(truncating: duration as NSNumber)))
  413. .foregroundColor(!displayPickerDuration ? .primary : .accentColor)
  414. .onTapGesture {
  415. displayPickerDuration = toggleScrollWheel(displayPickerDuration)
  416. }
  417. }
  418. if displayPickerDuration {
  419. HStack {
  420. Picker(
  421. selection: Binding(
  422. get: {
  423. Int(truncating: duration as NSNumber) / 60
  424. },
  425. set: {
  426. let minutes = Int(truncating: duration as NSNumber) % 60
  427. let totalMinutes = $0 * 60 + minutes
  428. duration = Decimal(totalMinutes)
  429. hasChanges = true
  430. }
  431. ),
  432. label: Text("")
  433. ) {
  434. ForEach(0 ..< 24) { hour in
  435. Text("\(hour) hr").tag(hour)
  436. }
  437. }
  438. .pickerStyle(WheelPickerStyle())
  439. .frame(maxWidth: .infinity)
  440. Picker(
  441. selection: Binding(
  442. get: {
  443. Int(truncating: duration as NSNumber) %
  444. 60 // Convert Decimal to Int for modulus operation
  445. },
  446. set: {
  447. duration = Decimal((Int(truncating: duration as NSNumber) / 60) * 60 + $0)
  448. hasChanges = true
  449. }
  450. ),
  451. label: Text("")
  452. ) {
  453. ForEach(Array(stride(from: 0, through: 55, by: 5)), id: \.self) { minute in
  454. Text("\(minute) min").tag(minute)
  455. }
  456. }
  457. .pickerStyle(WheelPickerStyle())
  458. .frame(maxWidth: .infinity)
  459. }
  460. .listRowSeparator(.hidden, edges: .top)
  461. }
  462. }
  463. }
  464. .listRowBackground(Color.chart)
  465. }
  466. }
  467. private var saveButton: some View {
  468. let (isInvalid, errorMessage) = isOverrideInvalid()
  469. return Section(
  470. header:
  471. HStack {
  472. Spacer()
  473. Text(errorMessage ?? "").textCase(nil)
  474. .foregroundColor(colorScheme == .dark ? .orange : .accentColor)
  475. Spacer()
  476. },
  477. content: {
  478. Button(action: {
  479. saveChanges()
  480. do {
  481. guard let moc = override.managedObjectContext else { return }
  482. guard moc.hasChanges else { return }
  483. try moc.save()
  484. Task {
  485. await state.nightscoutManager.uploadProfiles()
  486. }
  487. // Disable previous active Override
  488. if let currentActiveOverride = state.currentActiveOverride {
  489. Task {
  490. await state.disableAllActiveOverrides(
  491. except: currentActiveOverride.objectID,
  492. createOverrideRunEntry: false
  493. )
  494. // Update View
  495. state.updateLatestOverrideConfiguration()
  496. }
  497. }
  498. hasChanges = false
  499. presentationMode.wrappedValue.dismiss()
  500. } catch {
  501. debugPrint("\(DebuggingIdentifiers.failed) \(#file) \(#function) Failed to edit Override")
  502. }
  503. }, label: {
  504. Text("Save Override")
  505. })
  506. .disabled(isInvalid) // Disable button if changes are invalid
  507. .frame(maxWidth: .infinity, alignment: .center)
  508. .tint(.white)
  509. }
  510. )
  511. .listRowBackground(isInvalid ? Color(.systemGray4) : Color(.systemBlue))
  512. }
  513. private func isOverrideInvalid() -> (Bool, String?) {
  514. let noDurationSpecified = !indefinite && duration == 0
  515. let targetZeroWithOverride = target_override && (target ?? 0 < 72 || target ?? 0 > 270)
  516. let allSettingsDefault = percentage == 100 && !target_override && !advancedSettings &&
  517. !smbIsOff && !smbIsScheduledOff
  518. if noDurationSpecified {
  519. return (true, "Enable indefinitely or set a duration.")
  520. }
  521. if targetZeroWithOverride {
  522. return (true, "Target glucose is out of range (\(state.units == .mgdL ? "72-270" : "4-14")).")
  523. }
  524. if allSettingsDefault {
  525. return (true, "All settings are at default values.")
  526. }
  527. if !hasChanges {
  528. return (true, nil)
  529. }
  530. return (false, nil)
  531. }
  532. private func saveChanges() {
  533. if !override.isPreset, hasChanges, name == (override.name ?? "") {
  534. override.name = "Custom Override"
  535. } else {
  536. override.name = name
  537. }
  538. override.percentage = percentage
  539. override.indefinite = indefinite
  540. override.duration = NSDecimalNumber(decimal: duration)
  541. override.target = target_override ? NSDecimalNumber(decimal: target ?? 100) : nil
  542. override.advancedSettings = advancedSettings
  543. override.smbIsOff = smbIsOff
  544. override.smbIsScheduledOff = smbIsScheduledOff
  545. override.start = start.map { NSDecimalNumber(decimal: $0) }
  546. override.end = end.map { NSDecimalNumber(decimal: $0) }
  547. override.isfAndCr = isfAndCr
  548. override.isf = isf
  549. override.cr = cr
  550. override.smbMinutes = smbMinutes.map { NSDecimalNumber(decimal: $0) }
  551. override.uamMinutes = uamMinutes.map { NSDecimalNumber(decimal: $0) }
  552. override.isUploadedToNS = false
  553. }
  554. private func resetValues() {
  555. name = override.name ?? ""
  556. percentage = override.percentage
  557. indefinite = override.indefinite
  558. duration = override.duration?.decimalValue ?? 0
  559. target = override.target?.decimalValue
  560. advancedSettings = override.advancedSettings
  561. smbIsOff = override.smbIsOff
  562. smbIsScheduledOff = override.smbIsScheduledOff
  563. start = override.start?.decimalValue
  564. end = override.end?.decimalValue
  565. isfAndCr = override.isfAndCr
  566. isf = override.isf
  567. cr = override.cr
  568. smbMinutes = override.smbMinutes?.decimalValue ?? state.defaultSmbMinutes
  569. uamMinutes = override.uamMinutes?.decimalValue ?? state.defaultUamMinutes
  570. }
  571. private func toggleScrollWheel(_ toggle: Bool) -> Bool {
  572. displayPickerDuration = false
  573. displayPickerPercentage = false
  574. displayPickerTarget = false
  575. displayPickerDisableSmbSchedule = false
  576. displayPickerSmbMinutes = false
  577. return !toggle
  578. }
  579. }