OverrideProfilesRootView.swift 21 KB

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