AddOverrideForm.swift 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536
  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 selectedApplyToOption: ApplyToOption = .isfAndCr
  7. @State private var displayPickerDuration: Bool = false
  8. @State private var displayPickerStart: Bool = false
  9. @State private var displayPickerEnd: Bool = false
  10. @State private var displayPickerSmbMinutes: Bool = false
  11. @State private var displayPickerUamMinutes: Bool = false
  12. @State private var durationHours = 0
  13. @State private var durationMinutes = 0
  14. @State private var overrideTarget = false
  15. @Environment(\.colorScheme) var colorScheme
  16. @State private var showAlert = false
  17. @State private var alertString = ""
  18. @Environment(\.dismiss) var dismiss
  19. enum ApplyToOption: String, CaseIterable {
  20. case isfAndCr = "ISF/CR"
  21. case isf = "ISF"
  22. case cr = "CR"
  23. case none = "None"
  24. }
  25. var color: LinearGradient {
  26. colorScheme == .dark ? LinearGradient(
  27. gradient: Gradient(colors: [
  28. Color.bgDarkBlue,
  29. Color.bgDarkerDarkBlue
  30. ]),
  31. startPoint: .top,
  32. endPoint: .bottom
  33. )
  34. :
  35. LinearGradient(
  36. gradient: Gradient(colors: [Color.gray.opacity(0.1)]),
  37. startPoint: .top,
  38. endPoint: .bottom
  39. )
  40. }
  41. private var formatter: NumberFormatter {
  42. let formatter = NumberFormatter()
  43. formatter.numberStyle = .decimal
  44. formatter.maximumFractionDigits = 0
  45. return formatter
  46. }
  47. private var glucoseFormatter: NumberFormatter {
  48. let formatter = NumberFormatter()
  49. formatter.numberStyle = .decimal
  50. formatter.maximumFractionDigits = 0
  51. if state.units == .mmolL {
  52. formatter.maximumFractionDigits = 1
  53. }
  54. formatter.roundingMode = .halfUp
  55. return formatter
  56. }
  57. private var alertMessage: String {
  58. let target: String = state.units == .mgdL ? "70-270 mg/dl" : "4-15 mmol/l"
  59. return "Please enter a valid target between" + " \(target)."
  60. }
  61. var body: some View {
  62. NavigationView {
  63. Form {
  64. addOverride()
  65. }.scrollContentBackground(.hidden).background(color)
  66. .navigationTitle("Add Override")
  67. .navigationBarItems(trailing: Button("Cancel") {
  68. presentationMode.wrappedValue.dismiss()
  69. })
  70. }
  71. }
  72. @ViewBuilder private func addOverride() -> some View {
  73. Section {
  74. VStack {
  75. HStack {
  76. Text("Name")
  77. Spacer()
  78. TextField("(Optional)", text: $state.overrideName).multilineTextAlignment(.trailing)
  79. }
  80. }
  81. VStack {
  82. HStack {
  83. Spacer()
  84. // Decrement button
  85. Button(action: {
  86. if state.overrideSliderPercentage > 10 {
  87. state.overrideSliderPercentage -= 1
  88. }
  89. }) {
  90. Image(systemName: "minus.circle.fill")
  91. .font(.title)
  92. .foregroundColor(state.overrideSliderPercentage > 10 ? .accentColor : .loopGray)
  93. }
  94. .buttonStyle(PlainButtonStyle())
  95. Spacer()
  96. Text("\(Int(state.overrideSliderPercentage)) %")
  97. .font(.largeTitle)
  98. .foregroundColor(.accentColor)
  99. Spacer()
  100. // Increment button
  101. Button(action: {
  102. if state.overrideSliderPercentage < 200 {
  103. state.overrideSliderPercentage += 1
  104. }
  105. }) {
  106. Image(systemName: "plus.circle.fill")
  107. .font(.title)
  108. .foregroundColor(state.overrideSliderPercentage < 200 ? .accentColor : .loopGray)
  109. }
  110. .buttonStyle(PlainButtonStyle())
  111. Spacer()
  112. }
  113. .padding()
  114. // Slider to adjust value
  115. Slider(
  116. value: $state.overrideSliderPercentage,
  117. in: 10 ... 200,
  118. step: 1
  119. )
  120. // Picker for ISF/CR settings
  121. Picker("Apply to", selection: $selectedApplyToOption) {
  122. ForEach(ApplyToOption.allCases, id: \.self) { option in
  123. Text(option.rawValue).tag(option)
  124. }
  125. }
  126. .pickerStyle(MenuPickerStyle())
  127. .onChange(of: selectedApplyToOption) { newValue in
  128. switch newValue {
  129. case .isfAndCr:
  130. state.isfAndCr = true
  131. state.isf = true
  132. state.cr = true
  133. case .isf:
  134. state.isfAndCr = false
  135. state.isf = true
  136. state.cr = false
  137. case .cr:
  138. state.isfAndCr = false
  139. state.isf = false
  140. state.cr = true
  141. case .none:
  142. state.isfAndCr = false
  143. state.isf = false
  144. state.cr = false
  145. }
  146. }
  147. }
  148. VStack {
  149. Toggle(isOn: $state.indefinite) {
  150. Text("Enable Indefinitely")
  151. }
  152. if !state.indefinite {
  153. VStack {
  154. HStack {
  155. Text("Duration")
  156. Spacer()
  157. Text(formatHrMin(Int(state.overrideDuration)))
  158. .foregroundColor(!displayPickerDuration ? .primary : .accentColor)
  159. }
  160. .onTapGesture {
  161. displayPickerDuration.toggle()
  162. }
  163. if displayPickerDuration {
  164. HStack {
  165. Picker("Hours", selection: $durationHours) {
  166. ForEach(0 ..< 24) { hour in
  167. Text("\(hour) hr").tag(hour)
  168. }
  169. }
  170. .pickerStyle(WheelPickerStyle())
  171. .frame(width: 100)
  172. .onChange(of: durationHours) { _ in
  173. state.overrideDuration = Decimal(totalDurationInMinutes())
  174. }
  175. Picker("Minutes", selection: $durationMinutes) {
  176. ForEach(Array(stride(from: 0, through: 55, by: 5)), id: \.self) { minute in
  177. Text("\(minute) min").tag(minute)
  178. }
  179. }
  180. .pickerStyle(WheelPickerStyle())
  181. .frame(width: 100)
  182. .onChange(of: durationMinutes) { _ in
  183. state.overrideDuration = Decimal(totalDurationInMinutes())
  184. }
  185. }
  186. }
  187. }
  188. .padding(.top)
  189. }
  190. }
  191. VStack {
  192. Toggle(isOn: $state.shouldOverrideTarget) {
  193. Text("Override Profile Target")
  194. }
  195. if state.shouldOverrideTarget {
  196. HStack {
  197. Text("Target Glucose")
  198. TextFieldWithToolBar(text: $state.target, placeholder: "0", numberFormatter: glucoseFormatter)
  199. Text(state.units.rawValue).foregroundColor(.secondary)
  200. }
  201. }
  202. }
  203. Toggle(isOn: $state.advancedSettings) {
  204. Text("More Options")
  205. }
  206. if state.advancedSettings {
  207. Toggle(isOn: Binding(
  208. get: { state.smbIsOff },
  209. set: { newValue in
  210. state.smbIsOff = newValue
  211. if newValue {
  212. state.smbIsScheduledOff = false
  213. }
  214. }
  215. )) {
  216. Text("Disable SMBs")
  217. }
  218. VStack {
  219. Toggle(isOn: Binding(
  220. get: { state.smbIsScheduledOff },
  221. set: { newValue in
  222. state.smbIsScheduledOff = newValue
  223. if newValue {
  224. state.smbIsOff = false
  225. }
  226. }
  227. )) {
  228. Text("Schedule When SMBs Are Disabled")
  229. }
  230. if state.smbIsScheduledOff {
  231. // First Hour SMBs Are Disabled
  232. VStack {
  233. HStack {
  234. Text("From")
  235. Spacer()
  236. Text(
  237. is24HourFormat() ? format24Hour(Int(truncating: state.start as NSNumber)) + ":00" :
  238. convertTo12HourFormat(Int(truncating: state.start as NSNumber))
  239. )
  240. .foregroundColor(!displayPickerStart ? .primary : .accentColor)
  241. }
  242. .onTapGesture {
  243. displayPickerStart.toggle()
  244. }
  245. if displayPickerStart {
  246. Picker(selection: Binding(
  247. get: { Int(truncating: state.start as NSNumber) },
  248. set: { state.start = Decimal($0) }
  249. ), label: Text("")) {
  250. ForEach(0 ..< 24, id: \.self) { hour in
  251. Text(is24HourFormat() ? format24Hour(hour) + ":00" : convertTo12HourFormat(hour))
  252. .tag(hour)
  253. }
  254. }
  255. .pickerStyle(WheelPickerStyle())
  256. .frame(maxWidth: .infinity)
  257. }
  258. }
  259. .padding(.top, 10)
  260. // First Hour SMBs Are Resumed
  261. VStack {
  262. HStack {
  263. Text("To")
  264. Spacer()
  265. Text(
  266. is24HourFormat() ? format24Hour(Int(truncating: state.end as NSNumber)) + ":00" :
  267. convertTo12HourFormat(Int(truncating: state.end as NSNumber))
  268. )
  269. .foregroundColor(!displayPickerEnd ? .primary : .accentColor)
  270. }
  271. .onTapGesture {
  272. displayPickerEnd.toggle()
  273. }
  274. if displayPickerEnd {
  275. Picker(selection: Binding(
  276. get: { Int(truncating: state.end as NSNumber) },
  277. set: { state.end = Decimal($0) }
  278. ), label: Text("")) {
  279. ForEach(0 ..< 24, id: \.self) { hour in
  280. Text(is24HourFormat() ? format24Hour(hour) + ":00" : convertTo12HourFormat(hour))
  281. .tag(hour)
  282. }
  283. }
  284. .pickerStyle(WheelPickerStyle())
  285. .frame(maxWidth: .infinity)
  286. }
  287. }
  288. .padding(.vertical, 10)
  289. }
  290. }
  291. if !state.smbIsOff {
  292. VStack {
  293. // SMB Minutes Picker
  294. VStack {
  295. HStack {
  296. Text("Max SMB Minutes")
  297. Spacer()
  298. Text("\(state.smbMinutes.formatted(.number)) min")
  299. .foregroundColor(!displayPickerSmbMinutes ? .primary : .accentColor)
  300. }
  301. .onTapGesture {
  302. displayPickerSmbMinutes.toggle()
  303. }
  304. if displayPickerSmbMinutes {
  305. Picker(selection: Binding(
  306. get: { Int(truncating: state.smbMinutes as NSNumber) },
  307. set: { state.smbMinutes = Decimal($0) }
  308. ), label: Text("")) {
  309. ForEach(Array(stride(from: 0, through: 180, by: 5)), id: \.self) { minute in
  310. Text("\(minute) min").tag(minute)
  311. }
  312. }
  313. .pickerStyle(WheelPickerStyle())
  314. .frame(maxWidth: .infinity)
  315. }
  316. }
  317. .padding(.top)
  318. // UAM SMB Minutes Picker
  319. VStack {
  320. HStack {
  321. Text("Max UAM SMB Minutes")
  322. Spacer()
  323. Text("\(state.uamMinutes.formatted(.number)) min")
  324. .foregroundColor(!displayPickerUamMinutes ? .primary : .accentColor)
  325. }
  326. .onTapGesture {
  327. displayPickerUamMinutes.toggle()
  328. }
  329. if displayPickerUamMinutes {
  330. Picker(selection: Binding(
  331. get: { Int(truncating: state.uamMinutes as NSNumber) },
  332. set: { state.uamMinutes = Decimal($0) }
  333. ), label: Text("")) {
  334. ForEach(Array(stride(from: 0, through: 180, by: 5)), id: \.self) { minute in
  335. Text("\(minute) min").tag(minute)
  336. }
  337. }
  338. .pickerStyle(WheelPickerStyle())
  339. .frame(maxWidth: .infinity)
  340. }
  341. }
  342. .padding(.top)
  343. }
  344. }
  345. }
  346. startAndSaveProfiles
  347. }
  348. header: { Text("Add custom Override") }
  349. footer: {
  350. Text(
  351. "Your profile ISF and CR will be inversely adjusted with the override percentage."
  352. )
  353. }.listRowBackground(Color.chart)
  354. }
  355. private var startAndSaveProfiles: some View {
  356. HStack {
  357. Button("Start New Override") {
  358. if !state.isInputInvalid(target: state.target) {
  359. showAlert.toggle()
  360. alertString = "\(state.overrideSliderPercentage.formatted(.number)) %, " +
  361. (
  362. state.overrideDuration > 0 || !state
  363. .indefinite ?
  364. (
  365. state
  366. .overrideDuration
  367. .formatted(.number.grouping(.never).rounded().precision(.fractionLength(0))) +
  368. " min."
  369. ) :
  370. NSLocalizedString(" infinite duration.", comment: "")
  371. ) +
  372. (
  373. (state.target == 0 || !state.shouldOverrideTarget) ? "" :
  374. (" Target: " + state.target.formatted() + " " + state.units.rawValue + ".")
  375. )
  376. +
  377. (
  378. state
  379. .smbIsOff ?
  380. NSLocalizedString(
  381. " SMBs are disabled either by schedule or during the entire duration.",
  382. comment: ""
  383. ) : ""
  384. )
  385. +
  386. "\n\n"
  387. +
  388. NSLocalizedString(
  389. "Starting this override will change your profiles and/or your Target Glucose used for looping during the entire selected duration. Tapping ”Start Override” will start your new Override or edit your current active Override.",
  390. comment: ""
  391. )
  392. }
  393. }
  394. .disabled(unChanged())
  395. .buttonStyle(BorderlessButtonStyle())
  396. .font(.callout)
  397. .controlSize(.mini)
  398. .alert(
  399. "Start Override",
  400. isPresented: $showAlert,
  401. actions: {
  402. Button("Cancel", role: .cancel) { state.isEnabled = false }
  403. Button("Start Override", role: .destructive) {
  404. Task {
  405. if state.indefinite { state.overrideDuration = 0 }
  406. state.isEnabled.toggle()
  407. await state.saveCustomOverride()
  408. await state.resetStateVariables()
  409. dismiss()
  410. }
  411. }
  412. },
  413. message: {
  414. Text(alertString)
  415. }
  416. )
  417. .alert(isPresented: $state.showInvalidTargetAlert) {
  418. Alert(
  419. title: Text("Invalid Input"),
  420. message: Text("\(state.alertMessage)"),
  421. dismissButton: .default(Text("OK")) { state.showInvalidTargetAlert = false }
  422. )
  423. }
  424. Button {
  425. Task {
  426. if !state.isInputInvalid(target: state.target) {
  427. await state.saveOverridePreset()
  428. dismiss()
  429. }
  430. }
  431. }
  432. label: { Text("Save as Preset") }
  433. .tint(.orange)
  434. .frame(maxWidth: .infinity, alignment: .trailing)
  435. .buttonStyle(BorderlessButtonStyle())
  436. .controlSize(.mini)
  437. .disabled(unChanged())
  438. }
  439. }
  440. private func totalDurationInMinutes() -> Int {
  441. let durationTotal = (durationHours * 60) + durationMinutes
  442. return max(0, durationTotal)
  443. }
  444. private func unChanged() -> Bool {
  445. let defaultProfile = state.overrideSliderPercentage == 100 && !state.shouldOverrideTarget && !state.advancedSettings
  446. let noDurationSpecified = !state.indefinite && state.overrideDuration == 0
  447. let targetZeroWithOverride = state.shouldOverrideTarget && state.target == 0
  448. let allSettingsDefault = state.overrideSliderPercentage == 100 && !state.shouldOverrideTarget && !state.smbIsOff && !state
  449. .smbIsScheduledOff && state.smbMinutes == state.defaultSmbMinutes && state.uamMinutes == state.defaultUamMinutes
  450. return defaultProfile || noDurationSpecified || targetZeroWithOverride || allSettingsDefault
  451. }
  452. }
  453. // Function to check if the phone is using 24-hour format
  454. func is24HourFormat() -> Bool {
  455. let formatter = DateFormatter()
  456. formatter.locale = Locale.current
  457. formatter.dateStyle = .none
  458. formatter.timeStyle = .short
  459. let dateString = formatter.string(from: Date())
  460. return !dateString.contains("AM") && !dateString.contains("PM")
  461. }
  462. // Helper function to convert hours to AM/PM format
  463. func convertTo12HourFormat(_ hour: Int) -> String {
  464. let formatter = DateFormatter()
  465. formatter.dateFormat = "h a"
  466. // Create a date from the hour and format it to AM/PM
  467. let calendar = Calendar.current
  468. let components = DateComponents(hour: hour)
  469. let date = calendar.date(from: components) ?? Date()
  470. return formatter.string(from: date)
  471. }
  472. // Helper function to format 24-hour numbers as two digits
  473. func format24Hour(_ hour: Int) -> String {
  474. String(format: "%02d", hour)
  475. }
  476. func formatHrMin(_ durationInMinutes: Int) -> String {
  477. let hours = durationInMinutes / 60
  478. let minutes = durationInMinutes % 60
  479. switch (hours, minutes) {
  480. case let (0, m):
  481. return "\(m) min"
  482. case let (h, 0):
  483. return "\(h) hr"
  484. default:
  485. return "\(hours) hr \(minutes) min"
  486. }
  487. }