AddOverrideForm.swift 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646
  1. import Foundation
  2. import SwiftUI
  3. struct AddOverrideForm: View {
  4. @Environment(\.presentationMode) var presentationMode
  5. @StateObject var state: OverrideConfig.StateModel
  6. @State private var selectedIsfCrOption: IsfAndOrCrOptions = .isfAndCr
  7. @State private var selectedDisableSmbOption: DisableSmbOptions = .dontDisable
  8. @State private var percentageStep: Int = 5
  9. @State private var displayPickerPercentage: Bool = false
  10. @State private var displayPickerDuration: Bool = false
  11. @State private var targetStep: Decimal = 5
  12. @State private var displayPickerTarget: Bool = false
  13. @State private var displayPickerDisableSmbSchedule: Bool = false
  14. @State private var displayPickerSmbMinutes: Bool = false
  15. @State private var durationHours = 0
  16. @State private var durationMinutes = 0
  17. @State private var overrideTarget = false
  18. @State private var didPressSave = false
  19. @Environment(\.colorScheme) var colorScheme
  20. @Environment(\.dismiss) var dismiss
  21. var color: LinearGradient {
  22. colorScheme == .dark ? LinearGradient(
  23. gradient: Gradient(colors: [
  24. Color.bgDarkBlue,
  25. Color.bgDarkerDarkBlue
  26. ]),
  27. startPoint: .top,
  28. endPoint: .bottom
  29. ) :
  30. LinearGradient(
  31. gradient: Gradient(colors: [Color.gray.opacity(0.1)]),
  32. startPoint: .top,
  33. endPoint: .bottom
  34. )
  35. }
  36. private var formatter: NumberFormatter {
  37. let formatter = NumberFormatter()
  38. formatter.numberStyle = .decimal
  39. formatter.maximumFractionDigits = 0
  40. return formatter
  41. }
  42. var body: some View {
  43. NavigationView {
  44. List {
  45. addOverride()
  46. saveButton
  47. }
  48. .listSectionSpacing(10)
  49. .padding(.top, 30)
  50. .ignoresSafeArea(edges: .top)
  51. .scrollContentBackground(.hidden).background(color)
  52. .navigationTitle("Add Override")
  53. .navigationBarTitleDisplayMode(.inline)
  54. .toolbar {
  55. ToolbarItem(placement: .topBarLeading) {
  56. Button(action: {
  57. presentationMode.wrappedValue.dismiss()
  58. }, label: {
  59. Text("Cancel")
  60. })
  61. }
  62. ToolbarItem(placement: .topBarTrailing) {
  63. Button(
  64. action: {
  65. state.isHelpSheetPresented.toggle()
  66. },
  67. label: {
  68. Image(systemName: "questionmark.circle")
  69. }
  70. )
  71. }
  72. }
  73. .onAppear { targetStep = state.units == .mgdL ? 5 : 9 }
  74. .sheet(isPresented: $state.isHelpSheetPresented) {
  75. NavigationStack {
  76. List {
  77. Text("Lorem Ipsum Dolor Sit Amet")
  78. }
  79. .padding(.trailing, 10)
  80. .navigationBarTitle("Help", displayMode: .inline)
  81. Button { state.isHelpSheetPresented.toggle() }
  82. label: { Text("Got it!").frame(maxWidth: .infinity, alignment: .center) }
  83. .buttonStyle(.bordered)
  84. .padding(.top)
  85. }
  86. .padding()
  87. .presentationDetents(
  88. [.fraction(0.9), .large],
  89. selection: $state.helpSheetDetent
  90. )
  91. }
  92. }
  93. }
  94. @ViewBuilder private func addOverride() -> some View {
  95. Group {
  96. Section {
  97. HStack {
  98. Text("Name")
  99. Spacer()
  100. TextField("(Optional)", text: $state.overrideName).multilineTextAlignment(.trailing)
  101. }
  102. }
  103. .listRowBackground(Color.chart)
  104. Section {
  105. Toggle(isOn: $state.indefinite) {
  106. Text("Enable Indefinitely")
  107. }
  108. if !state.indefinite {
  109. HStack {
  110. Text("Duration")
  111. Spacer()
  112. Text(formatHrMin(Int(state.overrideDuration)))
  113. .foregroundColor(!displayPickerDuration ? .primary : .accentColor)
  114. }
  115. .onTapGesture {
  116. displayPickerDuration.toggle()
  117. }
  118. if displayPickerDuration {
  119. HStack {
  120. Picker("Hours", selection: $durationHours) {
  121. ForEach(0 ..< 24) { hour in
  122. Text("\(hour) hr").tag(hour)
  123. }
  124. }
  125. .pickerStyle(WheelPickerStyle())
  126. .frame(maxWidth: .infinity)
  127. .onChange(of: durationHours) {
  128. state.overrideDuration = Decimal(totalDurationInMinutes())
  129. }
  130. Picker("Minutes", selection: $durationMinutes) {
  131. ForEach(Array(stride(from: 0, through: 55, by: 5)), id: \.self) { minute in
  132. Text("\(minute) min").tag(minute)
  133. }
  134. }
  135. .pickerStyle(WheelPickerStyle())
  136. .frame(maxWidth: .infinity)
  137. .onChange(of: durationMinutes) {
  138. state.overrideDuration = Decimal(totalDurationInMinutes())
  139. }
  140. }
  141. .listRowSeparator(.hidden, edges: .top)
  142. }
  143. }
  144. }
  145. .listRowBackground(Color.chart)
  146. Section(footer: percentageDescription(state.overridePercentage)) {
  147. // Percentage Picker
  148. HStack {
  149. Text("Change Basal Rate by")
  150. Spacer()
  151. Text("\(state.overridePercentage.formatted(.number)) %")
  152. .foregroundColor(!displayPickerPercentage ? .primary : .accentColor)
  153. }
  154. .onTapGesture {
  155. displayPickerPercentage.toggle()
  156. }
  157. if displayPickerPercentage {
  158. HStack {
  159. // Radio buttons and text on the left side
  160. VStack(alignment: .leading) {
  161. // Radio buttons for step iteration
  162. ForEach([1, 5], id: \.self) { step in
  163. RadioButton(isSelected: percentageStep == step, label: "\(step) %") {
  164. percentageStep = step
  165. state.overridePercentage = OverrideConfig.StateModel.roundOverridePercentageToStep(
  166. state.overridePercentage,
  167. step
  168. )
  169. }
  170. .padding(.top, 10)
  171. }
  172. }
  173. .frame(maxWidth: .infinity)
  174. Spacer()
  175. // Picker on the right side
  176. Picker(
  177. selection: Binding(
  178. get: { Int(truncating: state.overridePercentage as NSNumber) },
  179. set: { state.overridePercentage = Double($0) }
  180. ), label: Text("")
  181. ) {
  182. ForEach(Array(stride(from: 40, through: 150, by: percentageStep)), id: \.self) { percent in
  183. Text("\(percent) %").tag(percent)
  184. }
  185. }
  186. .pickerStyle(WheelPickerStyle())
  187. .frame(maxWidth: .infinity)
  188. }
  189. .frame(maxWidth: .infinity)
  190. .listRowSeparator(.hidden, edges: .top)
  191. }
  192. // Picker for ISF/CR settings
  193. Picker("Also Inversely Change", selection: $selectedIsfCrOption) {
  194. ForEach(IsfAndOrCrOptions.allCases, id: \.self) { option in
  195. Text(option.rawValue).tag(option)
  196. }
  197. }
  198. .pickerStyle(MenuPickerStyle())
  199. .onChange(of: selectedIsfCrOption) { _, newValue in
  200. switch newValue {
  201. case .isfAndCr:
  202. state.isfAndCr = true
  203. state.isf = true
  204. state.cr = true
  205. case .isf:
  206. state.isfAndCr = false
  207. state.isf = true
  208. state.cr = false
  209. case .cr:
  210. state.isfAndCr = false
  211. state.isf = false
  212. state.cr = true
  213. case .nothing:
  214. state.isfAndCr = false
  215. state.isf = false
  216. state.cr = false
  217. }
  218. }
  219. }
  220. .listRowBackground(Color.chart)
  221. Section {
  222. Toggle(isOn: $state.shouldOverrideTarget) {
  223. Text("Override Profile Target")
  224. }
  225. if state.shouldOverrideTarget {
  226. HStack {
  227. Text("Target Glucose")
  228. Spacer()
  229. Text(
  230. (state.units == .mgdL ? state.target.description : state.target.formattedAsMmolL) + " " + state
  231. .units.rawValue
  232. )
  233. .foregroundColor(!displayPickerTarget ? .primary : .accentColor)
  234. }
  235. .onTapGesture {
  236. displayPickerTarget.toggle()
  237. }
  238. if displayPickerTarget {
  239. HStack {
  240. // Radio buttons and text on the left side
  241. VStack(alignment: .leading) {
  242. // Radio buttons for step iteration
  243. let stepChoices: [Decimal] = state.units == .mgdL ? [1, 5] : [1, 9]
  244. ForEach(stepChoices, id: \.self) { step in
  245. let label = (state.units == .mgdL ? step.description : step.formattedAsMmolL) + " " +
  246. state.units.rawValue
  247. RadioButton(
  248. isSelected: targetStep == step,
  249. label: label
  250. ) {
  251. targetStep = step
  252. state.target = OverrideConfig.StateModel.roundTargetToStep(state.target, targetStep)
  253. }
  254. .padding(.top, 10)
  255. }
  256. }
  257. .frame(maxWidth: .infinity)
  258. Spacer()
  259. // Picker on the right side
  260. Picker(selection: Binding(
  261. get: { OverrideConfig.StateModel.roundTargetToStep(state.target, targetStep) },
  262. set: { state.target = $0 }
  263. ), label: Text("")) {
  264. ForEach(
  265. generateTargetPickerValues(),
  266. id: \.self
  267. ) { glucose in
  268. Text(
  269. (state.units == .mgdL ? glucose.description : glucose.formattedAsMmolL) + " " + state
  270. .units.rawValue
  271. )
  272. .tag(glucose)
  273. }
  274. }
  275. .pickerStyle(WheelPickerStyle())
  276. .frame(maxWidth: .infinity)
  277. }
  278. .listRowSeparator(.hidden, edges: .top)
  279. }
  280. }
  281. }
  282. .listRowBackground(Color.chart)
  283. Section {
  284. // Picker for ISF/CR settings
  285. Picker("Disable SMBs", selection: $selectedDisableSmbOption) {
  286. ForEach(DisableSmbOptions.allCases, id: \.self) { option in
  287. Text(option.rawValue).tag(option)
  288. }
  289. }
  290. .pickerStyle(MenuPickerStyle())
  291. .onChange(of: selectedDisableSmbOption) { _, newValue in
  292. switch newValue {
  293. case .dontDisable:
  294. state.smbIsOff = false
  295. state.smbIsScheduledOff = false
  296. case .disable:
  297. state.smbIsOff = true
  298. state.smbIsScheduledOff = false
  299. case .disableOnSchedule:
  300. state.smbIsOff = false
  301. state.smbIsScheduledOff = true
  302. }
  303. }
  304. if state.smbIsScheduledOff {
  305. // First Hour SMBs Are Disabled
  306. HStack {
  307. Text("From")
  308. Spacer()
  309. Text(
  310. is24HourFormat() ? format24Hour(Int(truncating: state.start as NSNumber)) + ":00" :
  311. convertTo12HourFormat(Int(truncating: state.start as NSNumber))
  312. )
  313. .foregroundColor(!displayPickerDisableSmbSchedule ? .primary : .accentColor)
  314. Spacer()
  315. Divider().frame(width: 1, height: 20)
  316. Spacer()
  317. Text("To")
  318. Spacer()
  319. Text(
  320. is24HourFormat() ? format24Hour(Int(truncating: state.end as NSNumber)) + ":00" :
  321. convertTo12HourFormat(Int(truncating: state.end as NSNumber))
  322. )
  323. .foregroundColor(!displayPickerDisableSmbSchedule ? .primary : .accentColor)
  324. Spacer()
  325. }
  326. .onTapGesture {
  327. displayPickerDisableSmbSchedule.toggle()
  328. }
  329. if displayPickerDisableSmbSchedule {
  330. HStack {
  331. // From Picker
  332. Picker(selection: Binding(
  333. get: { Int(truncating: state.start as NSNumber) },
  334. set: { state.start = Decimal($0) }
  335. ), label: Text("")) {
  336. ForEach(0 ..< 24, id: \.self) { hour in
  337. Text(is24HourFormat() ? format24Hour(hour) + ":00" : convertTo12HourFormat(hour))
  338. .tag(hour)
  339. }
  340. }
  341. .pickerStyle(WheelPickerStyle())
  342. .frame(maxWidth: .infinity)
  343. // To Picker
  344. Picker(selection: Binding(
  345. get: { Int(truncating: state.end as NSNumber) },
  346. set: { state.end = Decimal($0) }
  347. ), label: Text("")) {
  348. ForEach(0 ..< 24, id: \.self) { hour in
  349. Text(is24HourFormat() ? format24Hour(hour) + ":00" : convertTo12HourFormat(hour))
  350. .tag(hour)
  351. }
  352. }
  353. .pickerStyle(WheelPickerStyle())
  354. .frame(maxWidth: .infinity)
  355. }
  356. .listRowSeparator(.hidden, edges: .top)
  357. }
  358. }
  359. }
  360. .listRowBackground(Color.chart)
  361. if !state.smbIsOff {
  362. Section {
  363. Toggle(isOn: $state.advancedSettings) {
  364. Text("Override Max SMB Minutes")
  365. }
  366. if state.advancedSettings {
  367. // SMB Minutes Picker
  368. HStack {
  369. Text("SMB")
  370. Spacer()
  371. Text("\(state.smbMinutes.formatted(.number)) min")
  372. .foregroundColor(!displayPickerSmbMinutes ? .primary : .accentColor)
  373. Spacer()
  374. Divider().frame(width: 1, height: 20)
  375. Spacer()
  376. Text("UAM")
  377. Spacer()
  378. Text("\(state.uamMinutes.formatted(.number)) min")
  379. .foregroundColor(!displayPickerSmbMinutes ? .primary : .accentColor)
  380. }
  381. .onTapGesture {
  382. displayPickerSmbMinutes.toggle()
  383. }
  384. if displayPickerSmbMinutes {
  385. HStack {
  386. Picker(selection: Binding(
  387. get: { Int(truncating: state.smbMinutes as NSNumber) },
  388. set: { state.smbMinutes = Decimal($0) }
  389. ), label: Text("")) {
  390. ForEach(Array(stride(from: 0, through: 180, by: 5)), id: \.self) { minute in
  391. Text("\(minute) min").tag(minute)
  392. }
  393. }
  394. .pickerStyle(WheelPickerStyle())
  395. .frame(maxWidth: .infinity)
  396. Picker(selection: Binding(
  397. get: { Int(truncating: state.uamMinutes as NSNumber) },
  398. set: { state.uamMinutes = Decimal($0) }
  399. ), label: Text("")) {
  400. ForEach(Array(stride(from: 0, through: 180, by: 5)), id: \.self) { minute in
  401. Text("\(minute) min").tag(minute)
  402. }
  403. }
  404. .pickerStyle(WheelPickerStyle())
  405. .frame(maxWidth: .infinity)
  406. }
  407. .listRowSeparator(.hidden, edges: .top)
  408. }
  409. }
  410. }
  411. .listRowBackground(Color.chart)
  412. }
  413. }
  414. }
  415. private var saveButton: some View {
  416. let (isInvalid, errorMessage) = isOverrideInvalid()
  417. return Group {
  418. Section(
  419. header:
  420. HStack {
  421. Spacer()
  422. Text(errorMessage ?? "").textCase(nil)
  423. .foregroundColor(colorScheme == .dark ? .orange : .accentColor)
  424. Spacer()
  425. },
  426. content: {
  427. Button(action: {
  428. Task {
  429. if state.indefinite { state.overrideDuration = 0 }
  430. state.isEnabled.toggle()
  431. await state.saveCustomOverride()
  432. await state.resetStateVariables()
  433. dismiss()
  434. }
  435. }, label: {
  436. Text("Enact Override")
  437. })
  438. .disabled(isInvalid)
  439. .frame(maxWidth: .infinity, alignment: .center)
  440. .tint(.white)
  441. }
  442. ).listRowBackground(isInvalid ? Color(.systemGray4) : Color(.systemBlue))
  443. Section {
  444. Button(action: {
  445. Task {
  446. await state.saveOverridePreset()
  447. dismiss()
  448. }
  449. }, label: {
  450. Text("Save as Preset")
  451. })
  452. .disabled(isInvalid)
  453. .frame(maxWidth: .infinity, alignment: .center)
  454. .tint(.white)
  455. }
  456. .listRowBackground(
  457. isInvalid ? Color(.systemGray4) : Color.secondary
  458. )
  459. }
  460. }
  461. private func totalDurationInMinutes() -> Int {
  462. let durationTotal = (durationHours * 60) + durationMinutes
  463. return max(0, durationTotal)
  464. }
  465. private func isOverrideInvalid() -> (Bool, String?) {
  466. let noDurationSpecified = !state.indefinite && state.overrideDuration == 0
  467. let targetZeroWithOverride = state.shouldOverrideTarget && state.target == 0
  468. let allSettingsDefault = state.overridePercentage == 100 && !state.shouldOverrideTarget &&
  469. !state.advancedSettings && !state.smbIsOff && !state.smbIsScheduledOff
  470. if noDurationSpecified {
  471. return (true, "Enable indefinitely or set a duration.")
  472. }
  473. if targetZeroWithOverride {
  474. return (true, "Target glucose is out of range (\(state.units == .mgdL ? "72-270" : "4-14")).")
  475. }
  476. if allSettingsDefault {
  477. return (true, "All settings are at default values.")
  478. }
  479. return (false, nil)
  480. }
  481. func generateTargetPickerValues() -> [Decimal] {
  482. var values: [Decimal] = []
  483. var currentValue: Double = 72
  484. let step = Double(targetStep)
  485. // Adjust currentValue to be divisible by targetStep
  486. let remainder = currentValue.truncatingRemainder(dividingBy: step)
  487. if remainder != 0 {
  488. // Move currentValue up to the next value divisible by targetStep
  489. currentValue += (step - remainder)
  490. }
  491. // Now generate the picker values starting from currentValue
  492. while currentValue <= 270 {
  493. values.append(Decimal(currentValue))
  494. currentValue += step
  495. }
  496. // Glucose values are stored as mg/dl values, so Integers.
  497. // Filter out duplicate values when rounded to 1 decimal place.
  498. if state.units == .mmolL {
  499. // Use a Set to track unique values rounded to 1 decimal
  500. var uniqueRoundedValues = Set<String>()
  501. values = values.filter { value in
  502. let roundedValue = String(format: "%.1f", NSDecimalNumber(decimal: value.asMmolL).doubleValue)
  503. return uniqueRoundedValues.insert(roundedValue).inserted
  504. }
  505. }
  506. return values
  507. }
  508. }
  509. enum IsfAndOrCrOptions: String, CaseIterable {
  510. case isfAndCr = "ISF/CR"
  511. case isf = "ISF"
  512. case cr = "CR"
  513. case nothing = "None"
  514. }
  515. enum DisableSmbOptions: String, CaseIterable {
  516. case dontDisable = "Don't Disable"
  517. case disable = "Disable"
  518. case disableOnSchedule = "Disable on Schedule"
  519. }
  520. func percentageDescription(_ percent: Double) -> Text? {
  521. if percent.isNaN || percent == 100 { return nil }
  522. var description: String = "Insulin doses will be "
  523. if percent < 100 {
  524. description += "decreased by "
  525. } else {
  526. description += "increased by "
  527. }
  528. let deviationFrom100 = abs(percent - 100)
  529. description += String(format: "%.0f% %.", deviationFrom100)
  530. return Text(description)
  531. }
  532. // Function to check if the phone is using 24-hour format
  533. func is24HourFormat() -> Bool {
  534. let formatter = DateFormatter()
  535. formatter.locale = Locale.current
  536. formatter.dateStyle = .none
  537. formatter.timeStyle = .short
  538. let dateString = formatter.string(from: Date())
  539. return !dateString.contains("AM") && !dateString.contains("PM")
  540. }
  541. // Helper function to convert hours to AM/PM format
  542. func convertTo12HourFormat(_ hour: Int) -> String {
  543. let formatter = DateFormatter()
  544. formatter.dateFormat = "h a"
  545. // Create a date from the hour and format it to AM/PM
  546. let calendar = Calendar.current
  547. let components = DateComponents(hour: hour)
  548. let date = calendar.date(from: components) ?? Date()
  549. return formatter.string(from: date)
  550. }
  551. // Helper function to format 24-hour numbers as two digits
  552. func format24Hour(_ hour: Int) -> String {
  553. String(format: "%02d", hour)
  554. }
  555. //
  556. // func formatHrMin(_ durationInMinutes: Int) -> String {
  557. // let hours = durationInMinutes / 60
  558. // let minutes = durationInMinutes % 60
  559. //
  560. // switch (hours, minutes) {
  561. // case let (0, m):
  562. // return "\(m) min"
  563. // case let (h, 0):
  564. // return "\(h) hr"
  565. // default:
  566. // return "\(hours) hr \(minutes) min"
  567. // }
  568. // }
  569. //
  570. // struct RadioButton: View {
  571. // var isSelected: Bool
  572. // var label: String
  573. // var action: () -> Void
  574. //
  575. // var body: some View {
  576. // Button(action: {
  577. // action()
  578. // }) {
  579. // HStack {
  580. // Image(systemName: isSelected ? "largecircle.fill.circle" : "circle")
  581. // Text(label) // Add label inside the button to make it tappable
  582. // }
  583. // }
  584. // .buttonStyle(PlainButtonStyle())
  585. // }
  586. // }