AddOverrideForm.swift 18 KB

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