AddOverrideForm.swift 22 KB

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