AddOverrideForm.swift 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458
  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. }
  122. VStack {
  123. Toggle(isOn: $state.indefinite) {
  124. Text("Enable Indefinitely")
  125. }
  126. if !state.indefinite {
  127. HStack {
  128. Text("Duration")
  129. TextFieldWithToolBar(text: $state.overrideDuration, placeholder: "0", numberFormatter: formatter)
  130. Text("min").foregroundColor(.secondary)
  131. }
  132. }
  133. }
  134. VStack {
  135. Toggle(isOn: $state.shouldOverrideTarget) {
  136. Text("Override Profile Target")
  137. }
  138. if state.shouldOverrideTarget {
  139. HStack {
  140. Text("Target Glucose")
  141. TextFieldWithToolBar(text: $state.target, placeholder: "0", numberFormatter: glucoseFormatter)
  142. Text(state.units.rawValue).foregroundColor(.secondary)
  143. }
  144. }
  145. }
  146. Toggle(isOn: $state.advancedSettings) {
  147. Text("More Options")
  148. }
  149. if state.advancedSettings {
  150. Toggle(isOn: Binding(
  151. get: { state.smbIsOff },
  152. set: { newValue in
  153. state.smbIsOff = newValue
  154. if newValue {
  155. state.smbIsScheduledOff = false
  156. }
  157. }
  158. )) {
  159. Text("Disable SMBs")
  160. }
  161. VStack {
  162. Toggle(isOn: Binding(
  163. get: { state.smbIsScheduledOff },
  164. set: { newValue in
  165. state.smbIsScheduledOff = newValue
  166. if newValue {
  167. state.smbIsOff = false
  168. }
  169. }
  170. )) {
  171. Text("Schedule When SMBs Are Disabled")
  172. }
  173. if state.smbIsScheduledOff {
  174. // First Hour SMBs Are Disabled
  175. VStack {
  176. HStack {
  177. Text("From")
  178. Spacer()
  179. Text(
  180. is24HourFormat() ? format24Hour(Int(truncating: state.start as NSNumber)) + ":00" :
  181. convertTo12HourFormat(Int(truncating: state.start as NSNumber))
  182. )
  183. .foregroundColor(!displayPickerStart ? .primary : .accentColor)
  184. }
  185. .onTapGesture {
  186. displayPickerStart.toggle()
  187. }
  188. if displayPickerStart {
  189. Picker(selection: Binding(
  190. get: { Int(truncating: state.start as NSNumber) },
  191. set: { state.start = Decimal($0) }
  192. ), label: Text("")) {
  193. ForEach(0 ..< 24, id: \.self) { hour in
  194. Text(is24HourFormat() ? format24Hour(hour) + ":00" : convertTo12HourFormat(hour))
  195. .tag(hour)
  196. }
  197. }
  198. .pickerStyle(WheelPickerStyle())
  199. .frame(maxWidth: .infinity)
  200. }
  201. }
  202. .padding(.top, 10)
  203. // First Hour SMBs Are Resumed
  204. VStack {
  205. HStack {
  206. Text("To")
  207. Spacer()
  208. Text(
  209. is24HourFormat() ? format24Hour(Int(truncating: state.end as NSNumber)) + ":00" :
  210. convertTo12HourFormat(Int(truncating: state.end as NSNumber))
  211. )
  212. .foregroundColor(!displayPickerEnd ? .primary : .accentColor)
  213. }
  214. .onTapGesture {
  215. displayPickerEnd.toggle()
  216. }
  217. if displayPickerEnd {
  218. Picker(selection: Binding(
  219. get: { Int(truncating: state.end as NSNumber) },
  220. set: { state.end = Decimal($0) }
  221. ), label: Text("")) {
  222. ForEach(0 ..< 24, id: \.self) { hour in
  223. Text(is24HourFormat() ? format24Hour(hour) + ":00" : convertTo12HourFormat(hour))
  224. .tag(hour)
  225. }
  226. }
  227. .pickerStyle(WheelPickerStyle())
  228. .frame(maxWidth: .infinity)
  229. }
  230. }
  231. .padding(.vertical, 10)
  232. }
  233. }
  234. if !state.smbIsOff {
  235. VStack {
  236. // SMB Minutes Picker
  237. VStack {
  238. HStack {
  239. Text("Max SMB Minutes")
  240. Spacer()
  241. Text("\(state.smbMinutes.formatted(.number)) min")
  242. .foregroundColor(!displayPickerSmbMinutes ? .primary : .accentColor)
  243. }
  244. .onTapGesture {
  245. displayPickerSmbMinutes.toggle()
  246. }
  247. if displayPickerSmbMinutes {
  248. Picker(selection: Binding(
  249. get: { Int(truncating: state.smbMinutes as NSNumber) },
  250. set: { state.smbMinutes = Decimal($0) }
  251. ), label: Text("")) {
  252. ForEach(Array(stride(from: 0, through: 180, by: 5)), id: \.self) { minute in
  253. Text("\(minute) min").tag(minute)
  254. }
  255. }
  256. .pickerStyle(WheelPickerStyle())
  257. .frame(maxWidth: .infinity)
  258. }
  259. }
  260. .padding(.top)
  261. // UAM SMB Minutes Picker
  262. VStack {
  263. HStack {
  264. Text("Max UAM SMB Minutes")
  265. Spacer()
  266. Text("\(state.uamMinutes.formatted(.number)) min")
  267. .foregroundColor(!displayPickerUamMinutes ? .primary : .accentColor)
  268. }
  269. .onTapGesture {
  270. displayPickerUamMinutes.toggle()
  271. }
  272. if displayPickerUamMinutes {
  273. Picker(selection: Binding(
  274. get: { Int(truncating: state.uamMinutes as NSNumber) },
  275. set: { state.uamMinutes = Decimal($0) }
  276. ), label: Text("")) {
  277. ForEach(Array(stride(from: 0, through: 180, by: 5)), id: \.self) { minute in
  278. Text("\(minute) min").tag(minute)
  279. }
  280. }
  281. .pickerStyle(WheelPickerStyle())
  282. .frame(maxWidth: .infinity)
  283. }
  284. }
  285. .padding(.top)
  286. }
  287. }
  288. }
  289. startAndSaveProfiles
  290. }
  291. header: { Text("Add custom Override") }
  292. footer: {
  293. Text(
  294. "Your profile ISF and CR will be inversly adjusted with the override percentage."
  295. )
  296. }.listRowBackground(Color.chart)
  297. }
  298. private var startAndSaveProfiles: some View {
  299. HStack {
  300. Button("Start New Override") {
  301. if !state.isInputInvalid(target: state.target) {
  302. showAlert.toggle()
  303. alertString = "\(state.overrideSliderPercentage.formatted(.number)) %, " +
  304. (
  305. state.overrideDuration > 0 || !state
  306. .indefinite ?
  307. (
  308. state
  309. .overrideDuration
  310. .formatted(.number.grouping(.never).rounded().precision(.fractionLength(0))) +
  311. " min."
  312. ) :
  313. NSLocalizedString(" infinite duration.", comment: "")
  314. ) +
  315. (
  316. (state.target == 0 || !state.shouldOverrideTarget) ? "" :
  317. (" Target: " + state.target.formatted() + " " + state.units.rawValue + ".")
  318. )
  319. +
  320. (
  321. state
  322. .smbIsOff ?
  323. NSLocalizedString(
  324. " SMBs are disabled either by schedule or during the entire duration.",
  325. comment: ""
  326. ) : ""
  327. )
  328. +
  329. "\n\n"
  330. +
  331. NSLocalizedString(
  332. "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.",
  333. comment: ""
  334. )
  335. }
  336. }
  337. .disabled(unChanged())
  338. .buttonStyle(BorderlessButtonStyle())
  339. .font(.callout)
  340. .controlSize(.mini)
  341. .alert(
  342. "Start Override",
  343. isPresented: $showAlert,
  344. actions: {
  345. Button("Cancel", role: .cancel) { state.isEnabled = false }
  346. Button("Start Override", role: .destructive) {
  347. Task {
  348. if state.indefinite { state.overrideDuration = 0 }
  349. state.isEnabled.toggle()
  350. await state.saveCustomOverride()
  351. await state.resetStateVariables()
  352. dismiss()
  353. }
  354. }
  355. },
  356. message: {
  357. Text(alertString)
  358. }
  359. )
  360. .alert(isPresented: $state.showInvalidTargetAlert) {
  361. Alert(
  362. title: Text("Invalid Input"),
  363. message: Text("\(state.alertMessage)"),
  364. dismissButton: .default(Text("OK")) { state.showInvalidTargetAlert = false }
  365. )
  366. }
  367. Button {
  368. Task {
  369. if !state.isInputInvalid(target: state.target) {
  370. await state.saveOverridePreset()
  371. dismiss()
  372. }
  373. }
  374. }
  375. label: { Text("Save as Preset") }
  376. .tint(.orange)
  377. .frame(maxWidth: .infinity, alignment: .trailing)
  378. .buttonStyle(BorderlessButtonStyle())
  379. .controlSize(.mini)
  380. .disabled(unChanged())
  381. }
  382. }
  383. private func unChanged() -> Bool {
  384. let defaultProfile = state.overrideSliderPercentage == 100 && !state.shouldOverrideTarget && !state.advancedSettings
  385. let noDurationSpecified = !state.indefinite && state.overrideDuration == 0
  386. let targetZeroWithOverride = state.shouldOverrideTarget && state.target == 0
  387. let allSettingsDefault = state.overrideSliderPercentage == 100 && !state.shouldOverrideTarget && !state.smbIsOff && !state
  388. .smbIsScheduledOff && state.smbMinutes == state.defaultSmbMinutes && state.uamMinutes == state.defaultUamMinutes
  389. return defaultProfile || noDurationSpecified || targetZeroWithOverride || allSettingsDefault
  390. }
  391. }
  392. // Function to check if the phone is using 24-hour format
  393. func is24HourFormat() -> Bool {
  394. let formatter = DateFormatter()
  395. formatter.locale = Locale.current
  396. formatter.dateStyle = .none
  397. formatter.timeStyle = .short
  398. let dateString = formatter.string(from: Date())
  399. return !dateString.contains("AM") && !dateString.contains("PM")
  400. }
  401. // Helper function to convert hours to AM/PM format
  402. func convertTo12HourFormat(_ hour: Int) -> String {
  403. let formatter = DateFormatter()
  404. formatter.dateFormat = "h a"
  405. // Create a date from the hour and format it to AM/PM
  406. let calendar = Calendar.current
  407. let components = DateComponents(hour: hour)
  408. let date = calendar.date(from: components) ?? Date()
  409. return formatter.string(from: date)
  410. }
  411. // Helper function to format 24-hour numbers as two digits
  412. func format24Hour(_ hour: Int) -> String {
  413. String(format: "%02d", hour)
  414. }