EditOverrideForm.swift 27 KB

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