OverrideProfilesRootView.swift 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463
  1. import CoreData
  2. import SwiftUI
  3. import Swinject
  4. extension OverrideProfilesConfig {
  5. struct RootView: BaseView {
  6. let resolver: Resolver
  7. @StateObject var state = StateModel()
  8. @State private var isEditing = false
  9. @State private var showAlert = false
  10. @State private var showingDetail = false
  11. @State private var alertString = ""
  12. @State private var selectedPreset: OverridePresets?
  13. @State private var isEditSheetPresented: Bool = false
  14. @State private var alertSring = ""
  15. @State var isSheetPresented: Bool = false
  16. @Environment(\.dismiss) var dismiss
  17. @Environment(\.managedObjectContext) var moc
  18. @FetchRequest(
  19. entity: OverridePresets.entity(),
  20. sortDescriptors: [NSSortDescriptor(key: "name", ascending: true)], predicate: NSPredicate(
  21. format: "name != %@", "" as String
  22. )
  23. ) var fetchedProfiles: FetchedResults<OverridePresets>
  24. private var formatter: NumberFormatter {
  25. let formatter = NumberFormatter()
  26. formatter.numberStyle = .decimal
  27. formatter.maximumFractionDigits = 0
  28. return formatter
  29. }
  30. private var glucoseFormatter: NumberFormatter {
  31. let formatter = NumberFormatter()
  32. formatter.numberStyle = .decimal
  33. formatter.maximumFractionDigits = 0
  34. if state.units == .mmolL {
  35. formatter.maximumFractionDigits = 1
  36. }
  37. formatter.roundingMode = .halfUp
  38. return formatter
  39. }
  40. var presetPopover: some View {
  41. Form {
  42. nameSection(header: "Enter a name")
  43. settingsSection(header: "Settings to save")
  44. Section {
  45. Button("Save") {
  46. state.savePreset()
  47. isSheetPresented = false
  48. }
  49. .disabled(
  50. state.profileName.isEmpty || fetchedProfiles
  51. .contains(where: { $0.name == state.profileName })
  52. )
  53. Button("Cancel") {
  54. isSheetPresented = false
  55. }
  56. }
  57. }
  58. }
  59. var editPresetPopover: some View {
  60. Form {
  61. nameSection(header: "Keep or change name?")
  62. settingsSection(header: "New settings to save")
  63. Section {
  64. Button("Save") {
  65. guard let selectedPreset = selectedPreset else { return }
  66. state.updatePreset(selectedPreset)
  67. isEditSheetPresented = false
  68. }
  69. .disabled(state.profileName.isEmpty)
  70. Button("Cancel") {
  71. isEditSheetPresented = false
  72. }
  73. }
  74. }
  75. }
  76. @ViewBuilder private func nameSection(header: String) -> some View {
  77. Section {
  78. TextField("Profile override name", text: $state.profileName)
  79. } header: {
  80. Text(header)
  81. }
  82. }
  83. @ViewBuilder private func settingsSection(header: String) -> some View {
  84. Section(header: Text(header)) {
  85. let percentString = Text("Override: \(Int(state.percentage))%")
  86. let targetString = state
  87. .target != 0 ? Text("Target: \(state.target.formatted()) \(state.units.rawValue)") : Text("")
  88. let durationString = state
  89. ._indefinite ? Text("Duration: Indefinite") : Text("Duration: \(state.duration.formatted()) minutes")
  90. let isfString = state.isf ? Text("Change ISF") : Text("")
  91. let crString = state.cr ? Text("Change CR") : Text("")
  92. let smbString = state.smbIsOff ? Text("Disable SMB") : Text("")
  93. let scheduledSMBString = state.smbIsScheduledOff ? Text("SMB Schedule On") : Text("")
  94. let maxMinutesSMBString = state
  95. .smbMinutes != 0 ? Text("\(state.smbMinutes.formatted()) SMB Basal minutes") : Text("")
  96. let maxMinutesUAMString = state
  97. .uamMinutes != 0 ? Text("\(state.uamMinutes.formatted()) UAM Basal minutes") : Text("")
  98. VStack(alignment: .leading, spacing: 2) {
  99. percentString
  100. if targetString != Text("") { targetString }
  101. if durationString != Text("") { durationString }
  102. if isfString != Text("") { isfString }
  103. if crString != Text("") { crString }
  104. if smbString != Text("") { smbString }
  105. if scheduledSMBString != Text("") { scheduledSMBString }
  106. if maxMinutesSMBString != Text("") { maxMinutesSMBString }
  107. if maxMinutesUAMString != Text("") { maxMinutesUAMString }
  108. }
  109. .foregroundColor(.secondary)
  110. .font(.caption)
  111. }
  112. }
  113. var body: some View {
  114. Form {
  115. if state.presets.isNotEmpty {
  116. Section {
  117. ForEach(fetchedProfiles.indices, id: \.self) { index in
  118. let preset = fetchedProfiles[index]
  119. profilesView(for: preset)
  120. .swipeActions {
  121. Button(role: .destructive) {
  122. removeProfile(at: IndexSet(integer: index))
  123. } label: {
  124. Label("Delete", systemImage: "trash")
  125. }
  126. Button {
  127. selectedPreset = preset
  128. state.profileName = preset.name ?? ""
  129. isEditSheetPresented = true
  130. } label: {
  131. Label("Edit", systemImage: "square.and.pencil")
  132. }.tint(.blue)
  133. }
  134. }
  135. }
  136. header: { Text("Activate profile override") }
  137. footer: { VStack(alignment: .leading) {
  138. Text("Swipe left on a profile to edit or delete it.")
  139. Text("When you want to edit a profile:")
  140. HStack(alignment: .top) {
  141. Text(" •")
  142. Text(
  143. "First use the profile configurator below and select the settings you want to include."
  144. )
  145. }
  146. HStack(alignment: .top) {
  147. Text(" •")
  148. Text(
  149. "Then swipe left on the profile you want to change and click the edit symbol."
  150. )
  151. }
  152. HStack(alignment: .top) {
  153. Text(" •")
  154. Text(
  155. "In the pop-up: Use the existing profile name or enter a new name and click save - Done!"
  156. )
  157. }
  158. }
  159. }
  160. }
  161. Section {
  162. VStack {
  163. Slider(
  164. value: $state.percentage,
  165. in: 10 ... 200,
  166. step: 1,
  167. onEditingChanged: { editing in
  168. isEditing = editing
  169. }
  170. ).accentColor(state.percentage >= 130 ? .red : .blue)
  171. Text("\(state.percentage.formatted(.number)) %")
  172. .foregroundColor(
  173. state
  174. .percentage >= 130 ? .red :
  175. (isEditing ? .orange : .blue)
  176. )
  177. .font(.largeTitle)
  178. Spacer()
  179. Toggle(isOn: $state._indefinite) {
  180. Text("Enable indefinitely")
  181. }
  182. }
  183. if !state._indefinite {
  184. HStack {
  185. Text("Duration")
  186. DecimalTextField("0", value: $state.duration, formatter: formatter, cleanInput: false)
  187. Text("minutes").foregroundColor(.secondary)
  188. }
  189. }
  190. HStack {
  191. Toggle(isOn: $state.override_target) {
  192. Text("Override Profile Target")
  193. }
  194. }
  195. if state.override_target {
  196. HStack {
  197. Text("Target Glucose")
  198. DecimalTextField("0", value: $state.target, formatter: glucoseFormatter, cleanInput: false)
  199. Text(state.units.rawValue).foregroundColor(.secondary)
  200. }
  201. }
  202. HStack {
  203. Toggle(isOn: $state.advancedSettings) {
  204. Text("More options")
  205. }
  206. }
  207. if state.advancedSettings {
  208. HStack {
  209. Toggle(isOn: $state.smbIsOff) {
  210. Text("Always Disable SMBs")
  211. }
  212. }
  213. if !state.smbIsOff {
  214. HStack {
  215. Toggle(isOn: $state.smbIsScheduledOff) {
  216. Text("Schedule when SMBs are Off")
  217. }
  218. }
  219. if state.smbIsScheduledOff {
  220. HStack {
  221. Text("First Hour SMBs are Off (24 hours)")
  222. DecimalTextField("0", value: $state.start, formatter: formatter, cleanInput: false)
  223. Text("hour").foregroundColor(.secondary)
  224. }
  225. HStack {
  226. Text("First Hour SMBs are Resumed (24 hours)")
  227. DecimalTextField("0", value: $state.end, formatter: formatter, cleanInput: false)
  228. Text("hour").foregroundColor(.secondary)
  229. }
  230. }
  231. }
  232. HStack {
  233. Toggle(isOn: $state.isfAndCr) {
  234. Text("Change ISF and CR")
  235. }
  236. }
  237. if !state.isfAndCr {
  238. HStack {
  239. Toggle(isOn: $state.isf) {
  240. Text("Change ISF")
  241. }
  242. }
  243. HStack {
  244. Toggle(isOn: $state.cr) {
  245. Text("Change CR")
  246. }
  247. }
  248. }
  249. HStack {
  250. Text("SMB Minutes")
  251. DecimalTextField(
  252. "0",
  253. value: $state.smbMinutes,
  254. formatter: formatter,
  255. cleanInput: false
  256. )
  257. Text("minutes").foregroundColor(.secondary)
  258. }
  259. HStack {
  260. Text("UAM SMB Minutes")
  261. DecimalTextField(
  262. "0",
  263. value: $state.uamMinutes,
  264. formatter: formatter,
  265. cleanInput: false
  266. )
  267. Text("minutes").foregroundColor(.secondary)
  268. }
  269. }
  270. HStack {
  271. Button("Start new Profile") {
  272. showAlert.toggle()
  273. alertSring = "\(state.percentage.formatted(.number)) %, " +
  274. (
  275. state.duration > 0 || !state
  276. ._indefinite ?
  277. (
  278. state
  279. .duration
  280. .formatted(.number.grouping(.never).rounded().precision(.fractionLength(0))) +
  281. " min."
  282. ) :
  283. NSLocalizedString(" infinite duration.", comment: "")
  284. ) +
  285. (
  286. (state.target == 0 || !state.override_target) ? "" :
  287. (" Target: " + state.target.formatted() + " " + state.units.rawValue + ".")
  288. )
  289. +
  290. (
  291. state
  292. .smbIsOff ?
  293. NSLocalizedString(
  294. " SMBs are disabled either by schedule or during the entire duration.",
  295. comment: ""
  296. ) : ""
  297. )
  298. +
  299. "\n\n"
  300. +
  301. NSLocalizedString(
  302. "Starting this override will change your Profiles and/or your Target Glucose used for looping during the entire selected duration. Tapping ”Start Profile” will start your new profile or edit your current active profile.",
  303. comment: ""
  304. )
  305. }
  306. .disabled(unChanged())
  307. .buttonStyle(BorderlessButtonStyle())
  308. .font(.callout)
  309. .controlSize(.mini)
  310. .alert(
  311. "Start Profile",
  312. isPresented: $showAlert,
  313. actions: {
  314. Button("Cancel", role: .cancel) { state.isEnabled = false }
  315. Button("Start Profile", role: .destructive) {
  316. if state._indefinite { state.duration = 0 }
  317. state.isEnabled.toggle()
  318. state.saveSettings()
  319. dismiss()
  320. }
  321. },
  322. message: {
  323. Text(alertSring)
  324. }
  325. )
  326. Button {
  327. isSheetPresented = true
  328. }
  329. label: { Text("Save as Profile") }
  330. .tint(.orange)
  331. .frame(maxWidth: .infinity, alignment: .trailing)
  332. .buttonStyle(BorderlessButtonStyle())
  333. .font(.callout)
  334. .controlSize(.mini)
  335. .disabled(unChanged())
  336. }
  337. .sheet(isPresented: $isSheetPresented) {
  338. presetPopover
  339. }
  340. }
  341. header: { Text("Insulin") }
  342. footer: {
  343. Text(
  344. "Your profile basal insulin will be adjusted with the override percentage and your profile ISF and CR will be inversly adjusted with the percentage."
  345. )
  346. }
  347. Button("Return to Normal") {
  348. state.cancelProfile()
  349. dismiss()
  350. }
  351. .frame(maxWidth: .infinity, alignment: .center)
  352. .buttonStyle(BorderlessButtonStyle())
  353. .disabled(!state.isEnabled)
  354. .tint(.red)
  355. }
  356. .onAppear(perform: configureView)
  357. .onAppear { state.savedSettings() }
  358. .navigationBarTitle("Profiles")
  359. .navigationBarTitleDisplayMode(.automatic)
  360. .navigationBarItems(leading: Button("Close", action: state.hideModal))
  361. .sheet(isPresented: $isEditSheetPresented) {
  362. editPresetPopover
  363. .padding()
  364. }
  365. }
  366. @ViewBuilder private func profilesView(for preset: OverridePresets) -> some View {
  367. let target = state.units == .mmolL ? (((preset.target ?? 0) as NSDecimalNumber) as Decimal)
  368. .asMmolL : (preset.target ?? 0) as Decimal
  369. let duration = (preset.duration ?? 0) as Decimal
  370. let name = ((preset.name ?? "") == "") || (preset.name?.isEmpty ?? true) ? "" : preset.name!
  371. let percent = preset.percentage / 100
  372. let perpetual = preset.indefinite
  373. let durationString = perpetual ? "" : "\(formatter.string(from: duration as NSNumber)!)"
  374. let scheduledSMBstring = (preset.smbIsOff && preset.smbIsScheduledOff) ? "Scheduled SMBs" : ""
  375. let smbString = (preset.smbIsOff && scheduledSMBstring == "") ? "SMBs are off" : ""
  376. let targetString = target != 0 ? "\(glucoseFormatter.string(from: target as NSNumber)!)" : ""
  377. let maxMinutesSMB = (preset.smbMinutes as Decimal?) != nil ? (preset.smbMinutes ?? 0) as Decimal : 0
  378. let maxMinutesUAM = (preset.uamMinutes as Decimal?) != nil ? (preset.uamMinutes ?? 0) as Decimal : 0
  379. let isfString = preset.isf ? "ISF" : ""
  380. let crString = preset.cr ? "CR" : ""
  381. let dash = crString != "" ? "/" : ""
  382. let isfAndCRstring = isfString + dash + crString
  383. if name != "" {
  384. HStack {
  385. VStack {
  386. HStack {
  387. Text(name)
  388. Spacer()
  389. }
  390. HStack(spacing: 5) {
  391. Text(percent.formatted(.percent.grouping(.never).rounded().precision(.fractionLength(0))))
  392. if targetString != "" {
  393. Text(targetString)
  394. Text(targetString != "" ? state.units.rawValue : "")
  395. }
  396. if durationString != "" { Text(durationString + (perpetual ? "" : "min")) }
  397. if smbString != "" { Text(smbString).foregroundColor(.secondary).font(.caption) }
  398. if scheduledSMBstring != "" { Text(scheduledSMBstring) }
  399. if preset.advancedSettings {
  400. Text(maxMinutesSMB == 0 ? "" : maxMinutesSMB.formatted() + " SMB")
  401. Text(maxMinutesUAM == 0 ? "" : maxMinutesUAM.formatted() + " UAM")
  402. Text(isfAndCRstring)
  403. }
  404. Spacer()
  405. }
  406. .padding(.top, 2)
  407. .foregroundColor(.secondary)
  408. .font(.caption)
  409. }
  410. .contentShape(Rectangle())
  411. .onTapGesture {
  412. state.selectProfile(id_: preset.id ?? "")
  413. state.hideModal()
  414. }
  415. }
  416. }
  417. }
  418. private func unChanged() -> Bool {
  419. let defaultProfile = state.percentage == 100 && !state.override_target && !state.advancedSettings
  420. let noDurationSpecified = !state._indefinite && state.duration == 0
  421. let targetZeroWithOverride = state.override_target && state.target == 0
  422. let allSettingsDefault = state.percentage == 100 && !state.override_target && !state.smbIsOff && !state
  423. .smbIsScheduledOff && state.smbMinutes == state.defaultSmbMinutes && state.uamMinutes == state.defaultUamMinutes
  424. return defaultProfile || noDurationSpecified || targetZeroWithOverride || allSettingsDefault
  425. }
  426. private func removeProfile(at offsets: IndexSet) {
  427. for index in offsets {
  428. let language = fetchedProfiles[index]
  429. moc.delete(language)
  430. }
  431. do {
  432. try moc.save()
  433. } catch {
  434. // To do: add error
  435. }
  436. }
  437. }
  438. }