OverrideProfilesRootView.swift 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653
  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 alertSring = ""
  12. @State var isSheetPresented: Bool = false
  13. @State private var showCheckmark: Bool = false
  14. @State private var selectedPresetID: String?
  15. // temp targets
  16. @State private var isPromptPresented = false
  17. @State private var isRemoveAlertPresented = false
  18. @State private var removeAlert: Alert?
  19. @State private var isEditingTT = false
  20. @Environment(\.dismiss) var dismiss
  21. @Environment(\.managedObjectContext) var moc
  22. @Environment(\.colorScheme) var colorScheme
  23. var color: LinearGradient {
  24. colorScheme == .dark ? LinearGradient(
  25. gradient: Gradient(colors: [
  26. Color.bgDarkBlue,
  27. Color.bgDarkerDarkBlue
  28. ]),
  29. startPoint: .top,
  30. endPoint: .bottom
  31. )
  32. :
  33. LinearGradient(
  34. gradient: Gradient(colors: [Color.gray.opacity(0.1)]),
  35. startPoint: .top,
  36. endPoint: .bottom
  37. )
  38. }
  39. @FetchRequest(
  40. entity: OverridePresets.entity(),
  41. sortDescriptors: [NSSortDescriptor(key: "name", ascending: true)], predicate: NSPredicate(
  42. format: "name != %@", "" as String
  43. )
  44. ) var fetchedProfiles: FetchedResults<OverridePresets>
  45. @FetchRequest(
  46. entity: TempTargetsSlider.entity(),
  47. sortDescriptors: [NSSortDescriptor(key: "date", ascending: false)]
  48. ) var isEnabledArray: FetchedResults<TempTargetsSlider>
  49. private var formatter: NumberFormatter {
  50. let formatter = NumberFormatter()
  51. formatter.numberStyle = .decimal
  52. formatter.maximumFractionDigits = 0
  53. return formatter
  54. }
  55. private var glucoseFormatter: NumberFormatter {
  56. let formatter = NumberFormatter()
  57. formatter.numberStyle = .decimal
  58. formatter.maximumFractionDigits = 0
  59. if state.units == .mmolL {
  60. formatter.maximumFractionDigits = 1
  61. }
  62. formatter.roundingMode = .halfUp
  63. return formatter
  64. }
  65. var presetPopover: some View {
  66. Form {
  67. Section {
  68. TextField("Name Of Profile", text: $state.profileName)
  69. } header: { Text("Enter Name of Profile") }
  70. Section {
  71. Button("Save") {
  72. state.savePreset()
  73. isSheetPresented = false
  74. }
  75. .disabled(state.profileName.isEmpty || fetchedProfiles.filter({ $0.name == state.profileName }).isNotEmpty)
  76. Button("Cancel") {
  77. isSheetPresented = false
  78. }
  79. }
  80. }
  81. }
  82. var body: some View {
  83. VStack {
  84. Picker("Tab", selection: $state.selectedTab) {
  85. ForEach(Tab.allCases) { tab in
  86. Text(NSLocalizedString(tab.name, comment: "")).tag(tab)
  87. }
  88. }
  89. .pickerStyle(.segmented).padding(.horizontal, 10)
  90. Form {
  91. switch state.selectedTab {
  92. case .profiles: profiles()
  93. case .tempTargets: tempTargets() }
  94. }.scrollContentBackground(.hidden).background(color)
  95. .onAppear(perform: configureView)
  96. .onAppear { state.savedSettings() }
  97. .navigationBarTitle("Profiles")
  98. .navigationBarTitleDisplayMode(.large)
  99. }.background(color)
  100. }
  101. @ViewBuilder func profiles() -> some View {
  102. if state.presetsProfiles.isNotEmpty {
  103. Section {
  104. ForEach(fetchedProfiles) { preset in
  105. profilesView(for: preset)
  106. }.onDelete(perform: removeProfile)
  107. }.listRowBackground(Color.chart)
  108. }
  109. Section {
  110. VStack {
  111. Spacer()
  112. Text("\(state.percentageProfiles.formatted(.number)) %")
  113. .foregroundColor(
  114. state
  115. .percentageProfiles >= 130 ? .red :
  116. (isEditing ? .orange : Color.tabBar)
  117. )
  118. .font(.largeTitle)
  119. Slider(
  120. value: $state.percentageProfiles,
  121. in: 10 ... 200,
  122. step: 1,
  123. onEditingChanged: { editing in
  124. isEditing = editing
  125. }
  126. )
  127. Spacer()
  128. Toggle(isOn: $state._indefinite) {
  129. Text("Enable indefinitely")
  130. }
  131. }
  132. if !state._indefinite {
  133. HStack {
  134. Text("Duration")
  135. TextFieldWithToolBar(text: $state.durationProfile, placeholder: "0", numberFormatter: formatter)
  136. Text("minutes").foregroundColor(.secondary)
  137. }
  138. }
  139. HStack {
  140. Toggle(isOn: $state.override_target) {
  141. Text("Override Profile Target")
  142. }
  143. }
  144. if state.override_target {
  145. HStack {
  146. Text("Target Glucose")
  147. TextFieldWithToolBar(text: $state.target, placeholder: "0", numberFormatter: glucoseFormatter)
  148. Text(state.units.rawValue).foregroundColor(.secondary)
  149. }
  150. }
  151. HStack {
  152. Toggle(isOn: $state.advancedSettings) {
  153. Text("More options")
  154. }
  155. }
  156. if state.advancedSettings {
  157. HStack {
  158. Toggle(isOn: $state.smbIsOff) {
  159. Text("Disable SMBs")
  160. }
  161. }
  162. HStack {
  163. Toggle(isOn: $state.smbIsAlwaysOff) {
  164. Text("Schedule when SMBs are Off")
  165. }.disabled(!state.smbIsOff)
  166. }
  167. if state.smbIsAlwaysOff {
  168. HStack {
  169. Text("First Hour SMBs are Off (24 hours)")
  170. TextFieldWithToolBar(text: $state.start, placeholder: "0", numberFormatter: formatter)
  171. Text("hour").foregroundColor(.secondary)
  172. }
  173. HStack {
  174. Text("Last Hour SMBs are Off (24 hours)")
  175. TextFieldWithToolBar(text: $state.end, placeholder: "0", numberFormatter: formatter)
  176. Text("hour").foregroundColor(.secondary)
  177. }
  178. }
  179. HStack {
  180. Toggle(isOn: $state.isfAndCr) {
  181. Text("Change ISF and CR")
  182. }
  183. }
  184. if !state.isfAndCr {
  185. HStack {
  186. Toggle(isOn: $state.isf) {
  187. Text("Change ISF")
  188. }
  189. }
  190. HStack {
  191. Toggle(isOn: $state.cr) {
  192. Text("Change CR")
  193. }
  194. }
  195. }
  196. HStack {
  197. Text("SMB Minutes")
  198. TextFieldWithToolBar(text: $state.smbMinutes, placeholder: "0", numberFormatter: formatter)
  199. Text("minutes").foregroundColor(.secondary)
  200. }
  201. HStack {
  202. Text("UAM SMB Minutes")
  203. TextFieldWithToolBar(text: $state.uamMinutes, placeholder: "0", numberFormatter: formatter)
  204. Text("minutes").foregroundColor(.secondary)
  205. }
  206. }
  207. // MARK: TESTING
  208. HStack {
  209. Button("Start new Profile") {
  210. showAlert.toggle()
  211. alertSring = "\(state.percentageProfiles.formatted(.number)) %, " +
  212. (
  213. state.durationProfile > 0 || !state
  214. ._indefinite ?
  215. (
  216. state
  217. .durationProfile
  218. .formatted(.number.grouping(.never).rounded().precision(.fractionLength(0))) +
  219. " min."
  220. ) :
  221. NSLocalizedString(" infinite duration.", comment: "")
  222. ) +
  223. (
  224. (state.target == 0 || !state.override_target) ? "" :
  225. (" Target: " + state.target.formatted() + " " + state.units.rawValue + ".")
  226. )
  227. +
  228. (
  229. state
  230. .smbIsOff ?
  231. NSLocalizedString(
  232. " SMBs are disabled either by schedule or during the entire duration.",
  233. comment: ""
  234. ) : ""
  235. )
  236. +
  237. "\n\n"
  238. +
  239. NSLocalizedString(
  240. "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.",
  241. comment: ""
  242. )
  243. }
  244. .disabled(unChanged())
  245. .buttonStyle(BorderlessButtonStyle())
  246. .font(.callout)
  247. .controlSize(.mini)
  248. .alert(
  249. "Start Profile",
  250. isPresented: $showAlert,
  251. actions: {
  252. Button("Cancel", role: .cancel) { state.isEnabled = false }
  253. Button("Start Profile", role: .destructive) {
  254. if state._indefinite { state.durationProfile = 0 }
  255. state.isEnabled.toggle()
  256. state.saveSettings()
  257. dismiss()
  258. }
  259. },
  260. message: {
  261. Text(alertSring)
  262. }
  263. )
  264. Button {
  265. isSheetPresented = true
  266. }
  267. label: { Text("Save as Profile") }
  268. .tint(.orange)
  269. .frame(maxWidth: .infinity, alignment: .trailing)
  270. .buttonStyle(BorderlessButtonStyle())
  271. .controlSize(.mini)
  272. .disabled(unChanged())
  273. }
  274. .sheet(isPresented: $isSheetPresented) {
  275. presetPopover
  276. }
  277. // MARK: TESTING END
  278. }
  279. header: { Text("Insulin") }
  280. footer: {
  281. Text(
  282. "Your profile basal insulin will be adjusted with the override percentage and your profile ISF and CR will be inversly adjusted with the percentage."
  283. )
  284. }.listRowBackground(Color.chart)
  285. Button(action: {
  286. state.cancelProfile()
  287. dismiss()
  288. }, label: {
  289. HStack {
  290. Spacer()
  291. Text("Cancel Profile")
  292. Spacer()
  293. Image(systemName: "xmark.app")
  294. .font(.title)
  295. }
  296. })
  297. .frame(maxWidth: .infinity, alignment: .center)
  298. .disabled(!state.isEnabled)
  299. .listRowBackground(!state.isEnabled ? Color(.systemGray4) : Color(.systemRed))
  300. .tint(.white)
  301. }
  302. @ViewBuilder func tempTargets() -> some View {
  303. if !state.presetsTT.isEmpty {
  304. Section(header: Text("Presets")) {
  305. ForEach(state.presetsTT) { preset in
  306. presetView(for: preset)
  307. }
  308. }.listRowBackground(Color.chart)
  309. }
  310. HStack {
  311. Text("Experimental")
  312. Toggle(isOn: $state.viewPercantage) {}.controlSize(.mini)
  313. Image(systemName: "figure.highintensity.intervaltraining")
  314. Image(systemName: "fork.knife")
  315. }.listRowBackground(Color.chart)
  316. if state.viewPercantage {
  317. Section {
  318. VStack {
  319. Text("\(state.percentageTT.formatted(.number)) % Insulin")
  320. .foregroundColor(isEditingTT ? .orange : .blue)
  321. .font(.largeTitle)
  322. .padding(.vertical)
  323. Slider(
  324. value: $state.percentageTT,
  325. in: 15 ...
  326. min(Double(state.maxValue * 100), 200),
  327. step: 1,
  328. onEditingChanged: { editing in
  329. isEditingTT = editing
  330. }
  331. )
  332. // Only display target slider when not 100 %
  333. if state.percentageTT != 100 {
  334. Spacer()
  335. Divider()
  336. Text(
  337. (
  338. state
  339. .units == .mmolL ?
  340. "\(state.computeTarget().asMmolL.formatted(.number.grouping(.never).rounded().precision(.fractionLength(1)))) mmol/L" :
  341. "\(state.computeTarget().formatted(.number.grouping(.never).rounded().precision(.fractionLength(0)))) mg/dl"
  342. )
  343. + NSLocalizedString(" Target Glucose", comment: "")
  344. )
  345. .foregroundColor(.green)
  346. .padding(.vertical)
  347. Slider(
  348. value: $state.hbt,
  349. in: 101 ... 295,
  350. step: 1
  351. ).accentColor(.green)
  352. }
  353. }
  354. }.listRowBackground(Color.chart)
  355. } else {
  356. Section(header: Text("Custom")) {
  357. HStack {
  358. Text("Target")
  359. Spacer()
  360. TextFieldWithToolBar(text: $state.low, placeholder: "0", numberFormatter: formatter)
  361. Text(state.units.rawValue).foregroundColor(.secondary)
  362. }
  363. HStack {
  364. Text("Duration")
  365. Spacer()
  366. TextFieldWithToolBar(text: $state.durationTT, placeholder: "0", numberFormatter: formatter)
  367. Text("minutes").foregroundColor(.secondary)
  368. }
  369. DatePicker("Date", selection: $state.date)
  370. HStack {
  371. Button { state.enact() }
  372. label: { Text("Enact") }
  373. .disabled(state.durationTT == 0)
  374. .buttonStyle(BorderlessButtonStyle())
  375. .font(.callout)
  376. .controlSize(.mini)
  377. Button { isPromptPresented = true }
  378. label: { Text("Save as preset") }
  379. .disabled(state.durationTT == 0)
  380. .tint(.orange)
  381. .frame(maxWidth: .infinity, alignment: .trailing)
  382. .buttonStyle(BorderlessButtonStyle())
  383. .controlSize(.mini)
  384. }
  385. }.listRowBackground(Color.chart)
  386. }
  387. if state.viewPercantage {
  388. Section {
  389. HStack {
  390. Text("Duration")
  391. Spacer()
  392. TextFieldWithToolBar(text: $state.durationTT, placeholder: "0", numberFormatter: formatter)
  393. Text("minutes").foregroundColor(.secondary)
  394. }
  395. DatePicker("Date", selection: $state.date)
  396. HStack {
  397. Button { state.enact() }
  398. label: { Text("Enact") }
  399. .disabled(state.durationTT == 0)
  400. .buttonStyle(BorderlessButtonStyle())
  401. .font(.callout)
  402. .controlSize(.mini)
  403. Button { isPromptPresented = true }
  404. label: { Text("Save as preset") }
  405. .disabled(state.durationTT == 0)
  406. .tint(.orange)
  407. .frame(maxWidth: .infinity, alignment: .trailing)
  408. .buttonStyle(BorderlessButtonStyle())
  409. .controlSize(.mini)
  410. }
  411. }.listRowBackground(Color.chart)
  412. }
  413. Section {
  414. Button { state.cancel() }
  415. label: {
  416. HStack {
  417. Spacer()
  418. Text("Cancel Temp Target")
  419. Spacer()
  420. Image(systemName: "xmark.app")
  421. .font(.title)
  422. }
  423. }
  424. .frame(maxWidth: .infinity, alignment: .center)
  425. .disabled(state.storage.current() == nil)
  426. .listRowBackground(state.storage.current() == nil ? Color(.systemGray4) : Color(.systemRed))
  427. .tint(.white)
  428. }.popover(isPresented: $isPromptPresented) {
  429. Form {
  430. Section(header: Text("Enter preset name")) {
  431. TextField("Name", text: $state.newPresetName)
  432. Button {
  433. state.save()
  434. isPromptPresented = false
  435. }
  436. label: { Text("Save") }
  437. Button { isPromptPresented = false }
  438. label: { Text("Cancel") }
  439. }
  440. }
  441. }
  442. .onAppear {
  443. configureView()
  444. state.hbt = isEnabledArray.first?.hbt ?? 160
  445. }
  446. }
  447. private func presetView(for preset: TempTarget) -> some View {
  448. var low = preset.targetBottom
  449. var high = preset.targetTop
  450. if state.units == .mmolL {
  451. low = low?.asMmolL
  452. high = high?.asMmolL
  453. }
  454. let isSelected = preset.id == selectedPresetID
  455. return ZStack(alignment: .trailing, content: {
  456. HStack {
  457. VStack {
  458. HStack {
  459. Text(preset.displayName)
  460. Spacer()
  461. }
  462. HStack(spacing: 2) {
  463. Text(
  464. "\(formatter.string(from: (low ?? 0) as NSNumber)!) - \(formatter.string(from: (high ?? 0) as NSNumber)!)"
  465. )
  466. .foregroundColor(.secondary)
  467. .font(.caption)
  468. Text(state.units.rawValue)
  469. .foregroundColor(.secondary)
  470. .font(.caption)
  471. Text("for")
  472. .foregroundColor(.secondary)
  473. .font(.caption)
  474. Text("\(formatter.string(from: preset.duration as NSNumber)!)")
  475. .foregroundColor(.secondary)
  476. .font(.caption)
  477. Text("min")
  478. .foregroundColor(.secondary)
  479. .font(.caption)
  480. Spacer()
  481. }.padding(.top, 2)
  482. }
  483. .contentShape(Rectangle())
  484. .onTapGesture {
  485. state.enactPreset(id: preset.id)
  486. selectedPresetID = preset.id
  487. showCheckmark.toggle()
  488. // deactivate showCheckmark after 3 seconds
  489. DispatchQueue.main.asyncAfter(deadline: .now() + 3) {
  490. showCheckmark = false
  491. }
  492. }
  493. Image(systemName: "xmark.circle").foregroundColor(showCheckmark && isSelected ? Color.clear : Color.secondary)
  494. .contentShape(Rectangle())
  495. .padding(.vertical)
  496. .onTapGesture {
  497. removeAlert = Alert(
  498. title: Text("Are you sure?"),
  499. message: Text("Delete preset \"\(preset.displayName)\""),
  500. primaryButton: .destructive(Text("Delete"), action: { state.removePreset(id: preset.id) }),
  501. secondaryButton: .cancel()
  502. )
  503. isRemoveAlertPresented = true
  504. }
  505. .alert(isPresented: $isRemoveAlertPresented) {
  506. removeAlert!
  507. }
  508. }
  509. if showCheckmark && isSelected {
  510. // show checkmark to indicate if the preset was actually pressed
  511. Image(systemName: "checkmark.circle.fill")
  512. .imageScale(.large)
  513. .fontWeight(.bold)
  514. .foregroundStyle(Color.green)
  515. }
  516. })
  517. }
  518. @ViewBuilder private func profilesView(for preset: OverridePresets) -> some View {
  519. let target = state.units == .mmolL ? (((preset.target ?? 0) as NSDecimalNumber) as Decimal)
  520. .asMmolL : (preset.target ?? 0) as Decimal
  521. let duration = (preset.duration ?? 0) as Decimal
  522. let name = ((preset.name ?? "") == "") || (preset.name?.isEmpty ?? true) ? "" : preset.name!
  523. let percent = preset.percentage / 100
  524. let perpetual = preset.indefinite
  525. let durationString = perpetual ? "" : "\(formatter.string(from: duration as NSNumber)!)"
  526. let scheduledSMBstring = (preset.smbIsOff && preset.smbIsAlwaysOff) ? "Scheduled SMBs" : ""
  527. let smbString = (preset.smbIsOff && scheduledSMBstring == "") ? "SMBs are off" : ""
  528. let targetString = target != 0 ? "\(glucoseFormatter.string(from: target as NSNumber)!)" : ""
  529. let maxMinutesSMB = (preset.smbMinutes as Decimal?) != nil ? (preset.smbMinutes ?? 0) as Decimal : 0
  530. let maxMinutesUAM = (preset.uamMinutes as Decimal?) != nil ? (preset.uamMinutes ?? 0) as Decimal : 0
  531. let isfString = preset.isf ? "ISF" : ""
  532. let crString = preset.cr ? "CR" : ""
  533. let dash = crString != "" ? "/" : ""
  534. let isfAndCRstring = isfString + dash + crString
  535. let isSelected = preset.id == selectedPresetID
  536. if name != "" {
  537. ZStack(alignment: .trailing, content: {
  538. HStack {
  539. VStack {
  540. HStack {
  541. Text(name)
  542. Spacer()
  543. }
  544. HStack(spacing: 5) {
  545. Text(percent.formatted(.percent.grouping(.never).rounded().precision(.fractionLength(0))))
  546. if targetString != "" {
  547. Text(targetString)
  548. Text(targetString != "" ? state.units.rawValue : "")
  549. }
  550. if durationString != "" { Text(durationString + (perpetual ? "" : "min")) }
  551. if smbString != "" { Text(smbString).foregroundColor(.secondary).font(.caption) }
  552. if scheduledSMBstring != "" { Text(scheduledSMBstring) }
  553. if preset.advancedSettings {
  554. Text(maxMinutesSMB == 0 ? "" : maxMinutesSMB.formatted() + " SMB")
  555. Text(maxMinutesUAM == 0 ? "" : maxMinutesUAM.formatted() + " UAM")
  556. Text(isfAndCRstring)
  557. }
  558. Spacer()
  559. }
  560. .padding(.top, 2)
  561. .foregroundColor(.secondary)
  562. .font(.caption)
  563. }
  564. .contentShape(Rectangle())
  565. .onTapGesture {
  566. state.selectProfile(id_: preset.id ?? "")
  567. state.hideModal()
  568. showCheckmark.toggle()
  569. selectedPresetID = preset.id
  570. // deactivate showCheckmark after 3 seconds
  571. DispatchQueue.main.asyncAfter(deadline: .now() + 3) {
  572. showCheckmark = false
  573. }
  574. }
  575. }
  576. // show checkmark to indicate if the preset was actually pressed
  577. if showCheckmark && isSelected {
  578. Image(systemName: "checkmark.circle.fill")
  579. .imageScale(.large)
  580. .fontWeight(.bold)
  581. .foregroundStyle(Color.green)
  582. }
  583. })
  584. }
  585. }
  586. private func unChanged() -> Bool {
  587. let isChanged = (
  588. state.percentageProfiles == 100 && !state.override_target && !state.smbIsOff && !state
  589. .advancedSettings
  590. ) ||
  591. (!state._indefinite && state.durationProfile == 0) || (state.override_target && state.target == 0) ||
  592. (
  593. state.percentageProfiles == 100 && !state.override_target && !state.smbIsOff && state.isf && state.cr && state
  594. .smbMinutes == state.defaultSmbMinutes && state.uamMinutes == state.defaultUamMinutes
  595. )
  596. return isChanged
  597. }
  598. private func removeProfile(at offsets: IndexSet) {
  599. for index in offsets {
  600. let language = fetchedProfiles[index]
  601. moc.delete(language)
  602. }
  603. if moc.hasChanges {
  604. do {
  605. try moc.save()
  606. } catch {
  607. // To do: add error
  608. }
  609. }
  610. }
  611. }
  612. }