AddOverrideForm.swift 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529
  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 displayPickerPercentage: Bool = false
  9. @State private var displayPickerDuration: Bool = false
  10. @State private var displayPickerTarget: Bool = false
  11. @State private var displayPickerDisableSmbSchedule: Bool = false
  12. @State private var displayPickerSmbMinutes: Bool = false
  13. @State private var durationHours = 0
  14. @State private var durationMinutes = 0
  15. @State private var overrideTarget = false
  16. @State private var didPressSave = false
  17. @Environment(\.colorScheme) var colorScheme
  18. @Environment(\.dismiss) var dismiss
  19. enum isfAndOrCrOptions: String, CaseIterable {
  20. case isfAndCr = "ISF/CR"
  21. case isf = "ISF"
  22. case cr = "CR"
  23. case none = "None"
  24. }
  25. enum disableSmbOptions: String, CaseIterable {
  26. case dontDisable = "Don't Disable"
  27. case disable = "Disable"
  28. case disableOnSchedule = "Disable on Schedule"
  29. }
  30. var color: LinearGradient {
  31. colorScheme == .dark ? LinearGradient(
  32. gradient: Gradient(colors: [
  33. Color.bgDarkBlue,
  34. Color.bgDarkerDarkBlue
  35. ]),
  36. startPoint: .top,
  37. endPoint: .bottom
  38. ) :
  39. LinearGradient(
  40. gradient: Gradient(colors: [Color.gray.opacity(0.1)]),
  41. startPoint: .top,
  42. endPoint: .bottom
  43. )
  44. }
  45. private var formatter: NumberFormatter {
  46. let formatter = NumberFormatter()
  47. formatter.numberStyle = .decimal
  48. formatter.maximumFractionDigits = 0
  49. return formatter
  50. }
  51. private var glucoseFormatter: NumberFormatter {
  52. let formatter = NumberFormatter()
  53. formatter.numberStyle = .decimal
  54. formatter.maximumFractionDigits = 0
  55. if state.units == .mmolL {
  56. formatter.maximumFractionDigits = 1
  57. }
  58. formatter.roundingMode = .halfUp
  59. return formatter
  60. }
  61. var body: some View {
  62. NavigationView {
  63. List {
  64. addOverride()
  65. saveButton
  66. }
  67. .listSectionSpacing(10)
  68. .listRowSpacing(10)
  69. .padding(.top, 30)
  70. .ignoresSafeArea(edges: .top)
  71. .scrollContentBackground(.hidden).background(color)
  72. .navigationTitle("Add Override")
  73. .navigationBarTitleDisplayMode(.inline)
  74. .toolbar {
  75. ToolbarItem(placement: .topBarLeading) {
  76. Button(action: {
  77. presentationMode.wrappedValue.dismiss()
  78. }, label: {
  79. Text("Cancel")
  80. })
  81. }
  82. }
  83. }
  84. }
  85. @ViewBuilder private func addOverride() -> some View {
  86. Section {
  87. let pad: CGFloat = 3
  88. VStack {
  89. HStack {
  90. Text("Name")
  91. Spacer()
  92. TextField("(Optional)", text: $state.overrideName).multilineTextAlignment(.trailing)
  93. }
  94. .padding(.vertical, pad)
  95. }
  96. VStack {
  97. Toggle(isOn: $state.indefinite) {
  98. Text("Enable Indefinitely")
  99. }
  100. .padding(.vertical, pad)
  101. if !state.indefinite {
  102. HStack {
  103. Text("Duration")
  104. Spacer()
  105. Text(formatHrMin(Int(state.overrideDuration)))
  106. .foregroundColor(!displayPickerDuration ? .primary : .accentColor)
  107. }
  108. .padding(.vertical, pad)
  109. .onTapGesture {
  110. displayPickerDuration.toggle()
  111. }
  112. if displayPickerDuration {
  113. HStack {
  114. Picker("Hours", selection: $durationHours) {
  115. ForEach(0 ..< 24) { hour in
  116. Text("\(hour) hr").tag(hour)
  117. }
  118. }
  119. .pickerStyle(WheelPickerStyle())
  120. .frame(maxWidth: .infinity)
  121. .onChange(of: durationHours) {
  122. state.overrideDuration = Decimal(totalDurationInMinutes())
  123. }
  124. Picker("Minutes", selection: $durationMinutes) {
  125. ForEach(Array(stride(from: 0, through: 55, by: 5)), id: \.self) { minute in
  126. Text("\(minute) min").tag(minute)
  127. }
  128. }
  129. .pickerStyle(WheelPickerStyle())
  130. .frame(maxWidth: .infinity)
  131. .onChange(of: durationMinutes) {
  132. state.overrideDuration = Decimal(totalDurationInMinutes())
  133. }
  134. }
  135. }
  136. }
  137. }
  138. VStack {
  139. // Percentage Picker
  140. HStack {
  141. Text("Change Basal Rate by")
  142. Spacer()
  143. Text("\(state.overridePercentage.formatted(.number)) %")
  144. .foregroundColor(!displayPickerPercentage ? .primary : .accentColor)
  145. }
  146. .padding(.vertical, pad)
  147. .onTapGesture {
  148. displayPickerPercentage.toggle()
  149. }
  150. if displayPickerPercentage {
  151. Picker(selection: Binding(
  152. get: { Int(truncating: state.overridePercentage as NSNumber) },
  153. set: { state.overridePercentage = Double($0) }
  154. ), label: Text("")) {
  155. ForEach(Array(stride(from: 10, through: 200, by: 5)), id: \.self) { percent in
  156. Text("\(percent) %").tag(percent)
  157. }
  158. }
  159. .pickerStyle(WheelPickerStyle())
  160. .frame(maxWidth: .infinity)
  161. }
  162. // Picker for ISF/CR settings
  163. Picker("Also Inversely Change", selection: $selectedIsfCrOption) {
  164. ForEach(isfAndOrCrOptions.allCases, id: \.self) { option in
  165. Text(option.rawValue).tag(option)
  166. }
  167. }
  168. .padding(.top, pad)
  169. .pickerStyle(MenuPickerStyle())
  170. .onChange(of: selectedIsfCrOption) { _, newValue in
  171. switch newValue {
  172. case .isfAndCr:
  173. state.isfAndCr = true
  174. state.isf = true
  175. state.cr = true
  176. case .isf:
  177. state.isfAndCr = false
  178. state.isf = true
  179. state.cr = false
  180. case .cr:
  181. state.isfAndCr = false
  182. state.isf = false
  183. state.cr = true
  184. case .none:
  185. state.isfAndCr = false
  186. state.isf = false
  187. state.cr = false
  188. }
  189. }
  190. }
  191. VStack {
  192. Toggle(isOn: $state.shouldOverrideTarget) {
  193. Text("Override Profile Target")
  194. }
  195. .padding(.vertical, pad)
  196. if state.shouldOverrideTarget {
  197. VStack {
  198. HStack {
  199. Text("Target Glucose")
  200. Spacer()
  201. Text(formattedGlucose(glucose: state.target))
  202. .foregroundColor(!displayPickerTarget ? .primary : .accentColor)
  203. }
  204. .padding(.vertical, pad)
  205. .onTapGesture {
  206. displayPickerTarget.toggle()
  207. }
  208. if displayPickerTarget {
  209. let step = state.units == .mgdL ? 1 : 2
  210. Picker(selection: Binding(
  211. get: { Int(truncating: state.target as NSNumber) },
  212. set: { state.target = Decimal($0)
  213. }
  214. ), label: Text("")) {
  215. ForEach(
  216. Array(stride(from: 72, through: 270, by: step)),
  217. id: \.self
  218. ) { glucose in
  219. Text(formattedGlucose(glucose: Decimal(glucose)))
  220. .tag(glucose)
  221. }
  222. }
  223. .pickerStyle(WheelPickerStyle())
  224. .frame(maxWidth: .infinity)
  225. }
  226. }
  227. }
  228. }
  229. VStack {
  230. // Picker for ISF/CR settings
  231. Picker("Disable SMBs", selection: $selectedDisableSmbOption) {
  232. ForEach(disableSmbOptions.allCases, id: \.self) { option in
  233. Text(option.rawValue).tag(option)
  234. }
  235. }
  236. .padding(.vertical, pad)
  237. .pickerStyle(MenuPickerStyle())
  238. .onChange(of: selectedDisableSmbOption) { _, newValue in
  239. switch newValue {
  240. case .dontDisable:
  241. state.smbIsOff = false
  242. state.smbIsScheduledOff = false
  243. case .disable:
  244. state.smbIsOff = true
  245. state.smbIsScheduledOff = false
  246. case .disableOnSchedule:
  247. state.smbIsOff = false
  248. state.smbIsScheduledOff = true
  249. }
  250. }
  251. if state.smbIsScheduledOff {
  252. // First Hour SMBs Are Disabled
  253. VStack {
  254. HStack {
  255. Text("From")
  256. Spacer()
  257. Text(
  258. is24HourFormat() ? format24Hour(Int(truncating: state.start as NSNumber)) + ":00" :
  259. convertTo12HourFormat(Int(truncating: state.start as NSNumber))
  260. )
  261. .foregroundColor(!displayPickerDisableSmbSchedule ? .primary : .accentColor)
  262. Spacer()
  263. Divider().frame(width: 1, height: 20)
  264. Spacer()
  265. Text("To")
  266. Spacer()
  267. Text(
  268. is24HourFormat() ? format24Hour(Int(truncating: state.end as NSNumber)) + ":00" :
  269. convertTo12HourFormat(Int(truncating: state.end as NSNumber))
  270. )
  271. .foregroundColor(!displayPickerDisableSmbSchedule ? .primary : .accentColor)
  272. Spacer()
  273. }
  274. .padding(.vertical, pad)
  275. .onTapGesture {
  276. displayPickerDisableSmbSchedule.toggle()
  277. }
  278. if displayPickerDisableSmbSchedule {
  279. HStack {
  280. // From Picker
  281. Picker(selection: Binding(
  282. get: { Int(truncating: state.start as NSNumber) },
  283. set: { state.start = Decimal($0) }
  284. ), label: Text("")) {
  285. ForEach(0 ..< 24, id: \.self) { hour in
  286. Text(is24HourFormat() ? format24Hour(hour) + ":00" : convertTo12HourFormat(hour))
  287. .tag(hour)
  288. }
  289. }
  290. .pickerStyle(WheelPickerStyle())
  291. .frame(maxWidth: .infinity)
  292. // To Picker
  293. Picker(selection: Binding(
  294. get: { Int(truncating: state.end as NSNumber) },
  295. set: { state.end = Decimal($0) }
  296. ), label: Text("")) {
  297. ForEach(0 ..< 24, id: \.self) { hour in
  298. Text(is24HourFormat() ? format24Hour(hour) + ":00" : convertTo12HourFormat(hour))
  299. .tag(hour)
  300. }
  301. }
  302. .pickerStyle(WheelPickerStyle())
  303. .frame(maxWidth: .infinity)
  304. }
  305. }
  306. }
  307. }
  308. }
  309. if !state.smbIsOff {
  310. VStack {
  311. Toggle(isOn: $state.advancedSettings) {
  312. Text("Override Max SMB Minutes")
  313. }
  314. .padding(.vertical, pad)
  315. if state.advancedSettings {
  316. // SMB Minutes Picker
  317. VStack {
  318. HStack {
  319. Text("SMB")
  320. Spacer()
  321. Text("\(state.smbMinutes.formatted(.number)) min")
  322. .foregroundColor(!displayPickerSmbMinutes ? .primary : .accentColor)
  323. Spacer()
  324. Divider().frame(width: 1, height: 20)
  325. Spacer()
  326. Text("UAM")
  327. Spacer()
  328. Text("\(state.uamMinutes.formatted(.number)) min")
  329. .foregroundColor(!displayPickerSmbMinutes ? .primary : .accentColor)
  330. }
  331. .padding(.vertical, pad)
  332. .onTapGesture {
  333. displayPickerSmbMinutes.toggle()
  334. }
  335. if displayPickerSmbMinutes {
  336. HStack {
  337. Picker(selection: Binding(
  338. get: { Int(truncating: state.smbMinutes as NSNumber) },
  339. set: { state.smbMinutes = Decimal($0) }
  340. ), label: Text("")) {
  341. ForEach(Array(stride(from: 0, through: 180, by: 5)), id: \.self) { minute in
  342. Text("\(minute) min").tag(minute)
  343. }
  344. }
  345. .pickerStyle(WheelPickerStyle())
  346. .frame(maxWidth: .infinity)
  347. Picker(selection: Binding(
  348. get: { Int(truncating: state.uamMinutes as NSNumber) },
  349. set: { state.uamMinutes = Decimal($0) }
  350. ), label: Text("")) {
  351. ForEach(Array(stride(from: 0, through: 180, by: 5)), id: \.self) { minute in
  352. Text("\(minute) min").tag(minute)
  353. }
  354. }
  355. .pickerStyle(WheelPickerStyle())
  356. .frame(maxWidth: .infinity)
  357. }
  358. }
  359. }
  360. }
  361. }
  362. }
  363. }
  364. .listRowBackground(Color.chart)
  365. }
  366. private var saveButton: some View {
  367. let (isInvalid, errorMessage) = isOverrideInvalid()
  368. return Group {
  369. Section(
  370. header:
  371. HStack {
  372. Spacer()
  373. Text(errorMessage ?? "").textCase(nil)
  374. .foregroundColor(colorScheme == .dark ? .orange : .accentColor)
  375. Spacer()
  376. },
  377. content: {
  378. Button(action: {
  379. Task {
  380. if state.indefinite { state.overrideDuration = 0 }
  381. state.isEnabled.toggle()
  382. await state.saveCustomOverride()
  383. await state.resetStateVariables()
  384. dismiss()
  385. }
  386. }, label: {
  387. Text("Enact Override")
  388. })
  389. .disabled(isInvalid)
  390. .frame(maxWidth: .infinity, alignment: .center)
  391. .tint(.white)
  392. }
  393. ).listRowBackground(isInvalid ? Color(.systemGray4) : Color(.systemBlue))
  394. Section {
  395. Button(action: {
  396. Task {
  397. await state.saveOverridePreset()
  398. dismiss()
  399. }
  400. }, label: {
  401. Text("Save as Preset")
  402. })
  403. .disabled(isInvalid)
  404. .frame(maxWidth: .infinity, alignment: .center)
  405. .tint(.white)
  406. }
  407. .listRowBackground(
  408. isInvalid ? Color(.systemGray4) : Color.secondary
  409. )
  410. }
  411. }
  412. private func totalDurationInMinutes() -> Int {
  413. let durationTotal = (durationHours * 60) + durationMinutes
  414. return max(0, durationTotal)
  415. }
  416. private func isOverrideInvalid() -> (Bool, String?) {
  417. let noDurationSpecified = !state.indefinite && state.overrideDuration == 0
  418. let targetZeroWithOverride = state.shouldOverrideTarget && state.target == 0
  419. let allSettingsDefault = state.overridePercentage == 100 && !state.shouldOverrideTarget &&
  420. !state.advancedSettings && !state.smbIsOff && !state.smbIsScheduledOff
  421. if noDurationSpecified {
  422. return (true, "Enable indefinitely or set a duration.")
  423. }
  424. if targetZeroWithOverride {
  425. return (true, "Target glucose is out of range (\(state.units == .mgdL ? "72-270" : "4-14")).")
  426. }
  427. if allSettingsDefault {
  428. return (true, "All settings are at default values.")
  429. }
  430. return (false, nil)
  431. }
  432. private func formattedGlucose(glucose: Decimal) -> String {
  433. let formattedValue: String
  434. if state.units == .mgdL {
  435. formattedValue = glucoseFormatter.string(from: glucose as NSDecimalNumber) ?? "\(glucose)"
  436. } else {
  437. formattedValue = glucose.formattedAsMmolL
  438. }
  439. return "\(formattedValue) \(state.units.rawValue)"
  440. }
  441. }
  442. // Function to check if the phone is using 24-hour format
  443. func is24HourFormat() -> Bool {
  444. let formatter = DateFormatter()
  445. formatter.locale = Locale.current
  446. formatter.dateStyle = .none
  447. formatter.timeStyle = .short
  448. let dateString = formatter.string(from: Date())
  449. return !dateString.contains("AM") && !dateString.contains("PM")
  450. }
  451. // Helper function to convert hours to AM/PM format
  452. func convertTo12HourFormat(_ hour: Int) -> String {
  453. let formatter = DateFormatter()
  454. formatter.dateFormat = "h a"
  455. // Create a date from the hour and format it to AM/PM
  456. let calendar = Calendar.current
  457. let components = DateComponents(hour: hour)
  458. let date = calendar.date(from: components) ?? Date()
  459. return formatter.string(from: date)
  460. }
  461. // Helper function to format 24-hour numbers as two digits
  462. func format24Hour(_ hour: Int) -> String {
  463. String(format: "%02d", hour)
  464. }
  465. func formatHrMin(_ durationInMinutes: Int) -> String {
  466. let hours = durationInMinutes / 60
  467. let minutes = durationInMinutes % 60
  468. switch (hours, minutes) {
  469. case let (0, m):
  470. return "\(m) min"
  471. case let (h, 0):
  472. return "\(h) hr"
  473. default:
  474. return "\(hours) hr \(minutes) min"
  475. }
  476. }