OverrideProfilesRootView.swift 21 KB

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