AddOverrideForm.swift 20 KB

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