OverrideProfilesRootView.swift 23 KB

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