OverrideProfilesRootView.swift 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661
  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.blue)
  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. DecimalTextField("0", value: $state.durationProfile, formatter: formatter, cleanInput: false)
  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. DecimalTextField("0", value: $state.target, formatter: glucoseFormatter, cleanInput: false)
  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. DecimalTextField("0", value: $state.start, formatter: formatter, cleanInput: false)
  171. Text("hour").foregroundColor(.secondary)
  172. }
  173. HStack {
  174. Text("Last Hour SMBs are Off (24 hours)")
  175. DecimalTextField("0", value: $state.end, formatter: formatter, cleanInput: false)
  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. DecimalTextField(
  199. "0",
  200. value: $state.smbMinutes,
  201. formatter: formatter,
  202. cleanInput: false
  203. )
  204. Text("minutes").foregroundColor(.secondary)
  205. }
  206. HStack {
  207. Text("UAM SMB Minutes")
  208. DecimalTextField(
  209. "0",
  210. value: $state.uamMinutes,
  211. formatter: formatter,
  212. cleanInput: false
  213. )
  214. Text("minutes").foregroundColor(.secondary)
  215. }
  216. }
  217. // MARK: TESTING
  218. HStack {
  219. Button("Start new Profile") {
  220. showAlert.toggle()
  221. alertSring = "\(state.percentageProfiles.formatted(.number)) %, " +
  222. (
  223. state.durationProfile > 0 || !state
  224. ._indefinite ?
  225. (
  226. state
  227. .durationProfile
  228. .formatted(.number.grouping(.never).rounded().precision(.fractionLength(0))) +
  229. " min."
  230. ) :
  231. NSLocalizedString(" infinite duration.", comment: "")
  232. ) +
  233. (
  234. (state.target == 0 || !state.override_target) ? "" :
  235. (" Target: " + state.target.formatted() + " " + state.units.rawValue + ".")
  236. )
  237. +
  238. (
  239. state
  240. .smbIsOff ?
  241. NSLocalizedString(
  242. " SMBs are disabled either by schedule or during the entire duration.",
  243. comment: ""
  244. ) : ""
  245. )
  246. +
  247. "\n\n"
  248. +
  249. NSLocalizedString(
  250. "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.",
  251. comment: ""
  252. )
  253. }
  254. .disabled(unChanged())
  255. .buttonStyle(BorderlessButtonStyle())
  256. .font(.callout)
  257. .controlSize(.mini)
  258. .alert(
  259. "Start Profile",
  260. isPresented: $showAlert,
  261. actions: {
  262. Button("Cancel", role: .cancel) { state.isEnabled = false }
  263. Button("Start Profile", role: .destructive) {
  264. if state._indefinite { state.durationProfile = 0 }
  265. state.isEnabled.toggle()
  266. state.saveSettings()
  267. dismiss()
  268. }
  269. },
  270. message: {
  271. Text(alertSring)
  272. }
  273. )
  274. Button {
  275. isSheetPresented = true
  276. }
  277. label: { Text("Save as Profile") }
  278. .tint(.orange)
  279. .frame(maxWidth: .infinity, alignment: .trailing)
  280. .buttonStyle(BorderlessButtonStyle())
  281. .controlSize(.mini)
  282. .disabled(unChanged())
  283. }
  284. .sheet(isPresented: $isSheetPresented) {
  285. presetPopover
  286. }
  287. // MARK: TESTING END
  288. }
  289. header: { Text("Insulin") }
  290. footer: {
  291. Text(
  292. "Your profile basal insulin will be adjusted with the override percentage and your profile ISF and CR will be inversly adjusted with the percentage."
  293. )
  294. }.listRowBackground(Color.chart)
  295. Button(action: {
  296. state.cancelProfile()
  297. dismiss()
  298. }, label: {
  299. HStack {
  300. Spacer()
  301. Text("Cancel Profile")
  302. Spacer()
  303. Image(systemName: "xmark.app")
  304. .font(.title)
  305. }
  306. })
  307. .frame(maxWidth: .infinity, alignment: .center)
  308. .disabled(!state.isEnabled)
  309. .listRowBackground(!state.isEnabled ? Color(.systemGray4) : Color(.systemRed))
  310. .tint(.white)
  311. }
  312. @ViewBuilder func tempTargets() -> some View {
  313. if !state.presetsTT.isEmpty {
  314. Section(header: Text("Presets")) {
  315. ForEach(state.presetsTT) { preset in
  316. presetView(for: preset)
  317. }
  318. }.listRowBackground(Color.chart)
  319. }
  320. HStack {
  321. Text("Experimental")
  322. Toggle(isOn: $state.viewPercantage) {}.controlSize(.mini)
  323. Image(systemName: "figure.highintensity.intervaltraining")
  324. Image(systemName: "fork.knife")
  325. }.listRowBackground(Color.chart)
  326. if state.viewPercantage {
  327. Section {
  328. VStack {
  329. Text("\(state.percentageTT.formatted(.number)) % Insulin")
  330. .foregroundColor(isEditingTT ? .orange : .blue)
  331. .font(.largeTitle)
  332. .padding(.vertical)
  333. Slider(
  334. value: $state.percentageTT,
  335. in: 15 ...
  336. min(Double(state.maxValue * 100), 200),
  337. step: 1,
  338. onEditingChanged: { editing in
  339. isEditingTT = editing
  340. }
  341. )
  342. // Only display target slider when not 100 %
  343. if state.percentageTT != 100 {
  344. Spacer()
  345. Divider()
  346. Text(
  347. (
  348. state
  349. .units == .mmolL ?
  350. "\(state.computeTarget().asMmolL.formatted(.number.grouping(.never).rounded().precision(.fractionLength(1)))) mmol/L" :
  351. "\(state.computeTarget().formatted(.number.grouping(.never).rounded().precision(.fractionLength(0)))) mg/dl"
  352. )
  353. + NSLocalizedString(" Target Glucose", comment: "")
  354. )
  355. .foregroundColor(.green)
  356. .padding(.vertical)
  357. Slider(
  358. value: $state.hbt,
  359. in: 101 ... 295,
  360. step: 1
  361. ).accentColor(.green)
  362. }
  363. }
  364. }.listRowBackground(Color.chart)
  365. } else {
  366. Section(header: Text("Custom")) {
  367. HStack {
  368. Text("Target")
  369. Spacer()
  370. DecimalTextField("0", value: $state.low, formatter: formatter, cleanInput: true)
  371. Text(state.units.rawValue).foregroundColor(.secondary)
  372. }
  373. HStack {
  374. Text("Duration")
  375. Spacer()
  376. DecimalTextField("0", value: $state.durationTT, formatter: formatter, cleanInput: true)
  377. Text("minutes").foregroundColor(.secondary)
  378. }
  379. DatePicker("Date", selection: $state.date)
  380. HStack {
  381. Button { state.enact() }
  382. label: { Text("Enact") }
  383. .disabled(state.durationTT == 0)
  384. .buttonStyle(BorderlessButtonStyle())
  385. .font(.callout)
  386. .controlSize(.mini)
  387. Button { isPromptPresented = true }
  388. label: { Text("Save as preset") }
  389. .disabled(state.durationTT == 0)
  390. .tint(.orange)
  391. .frame(maxWidth: .infinity, alignment: .trailing)
  392. .buttonStyle(BorderlessButtonStyle())
  393. .controlSize(.mini)
  394. }
  395. }.listRowBackground(Color.chart)
  396. }
  397. if state.viewPercantage {
  398. Section {
  399. HStack {
  400. Text("Duration")
  401. Spacer()
  402. DecimalTextField("0", value: $state.durationTT, formatter: formatter, cleanInput: true)
  403. Text("minutes").foregroundColor(.secondary)
  404. }
  405. DatePicker("Date", selection: $state.date)
  406. HStack {
  407. Button { state.enact() }
  408. label: { Text("Enact") }
  409. .disabled(state.durationTT == 0)
  410. .buttonStyle(BorderlessButtonStyle())
  411. .font(.callout)
  412. .controlSize(.mini)
  413. Button { isPromptPresented = true }
  414. label: { Text("Save as preset") }
  415. .disabled(state.durationTT == 0)
  416. .tint(.orange)
  417. .frame(maxWidth: .infinity, alignment: .trailing)
  418. .buttonStyle(BorderlessButtonStyle())
  419. .controlSize(.mini)
  420. }
  421. }.listRowBackground(Color.chart)
  422. }
  423. Section {
  424. Button { state.cancel() }
  425. label: {
  426. HStack {
  427. Spacer()
  428. Text("Cancel Temp Target")
  429. Spacer()
  430. Image(systemName: "xmark.app")
  431. .font(.title)
  432. }
  433. }
  434. .frame(maxWidth: .infinity, alignment: .center)
  435. .disabled(state.storage.current() == nil)
  436. .listRowBackground(state.storage.current() == nil ? Color(.systemGray4) : Color(.systemRed))
  437. .tint(.white)
  438. }.popover(isPresented: $isPromptPresented) {
  439. Form {
  440. Section(header: Text("Enter preset name")) {
  441. TextField("Name", text: $state.newPresetName)
  442. Button {
  443. state.save()
  444. isPromptPresented = false
  445. }
  446. label: { Text("Save") }
  447. Button { isPromptPresented = false }
  448. label: { Text("Cancel") }
  449. }
  450. }
  451. }
  452. .onAppear {
  453. configureView()
  454. state.hbt = isEnabledArray.first?.hbt ?? 160
  455. }
  456. }
  457. private func presetView(for preset: TempTarget) -> some View {
  458. var low = preset.targetBottom
  459. var high = preset.targetTop
  460. if state.units == .mmolL {
  461. low = low?.asMmolL
  462. high = high?.asMmolL
  463. }
  464. let isSelected = preset.id == selectedPresetID
  465. return ZStack(alignment: .trailing, content: {
  466. HStack {
  467. VStack {
  468. HStack {
  469. Text(preset.displayName)
  470. Spacer()
  471. }
  472. HStack(spacing: 2) {
  473. Text(
  474. "\(formatter.string(from: (low ?? 0) as NSNumber)!) - \(formatter.string(from: (high ?? 0) as NSNumber)!)"
  475. )
  476. .foregroundColor(.secondary)
  477. .font(.caption)
  478. Text(state.units.rawValue)
  479. .foregroundColor(.secondary)
  480. .font(.caption)
  481. Text("for")
  482. .foregroundColor(.secondary)
  483. .font(.caption)
  484. Text("\(formatter.string(from: preset.duration as NSNumber)!)")
  485. .foregroundColor(.secondary)
  486. .font(.caption)
  487. Text("min")
  488. .foregroundColor(.secondary)
  489. .font(.caption)
  490. Spacer()
  491. }.padding(.top, 2)
  492. }
  493. .contentShape(Rectangle())
  494. .onTapGesture {
  495. state.enactPreset(id: preset.id)
  496. selectedPresetID = preset.id
  497. showCheckmark.toggle()
  498. // deactivate showCheckmark after 3 seconds
  499. DispatchQueue.main.asyncAfter(deadline: .now() + 3) {
  500. showCheckmark = false
  501. }
  502. }
  503. Image(systemName: "xmark.circle").foregroundColor(showCheckmark && isSelected ? Color.clear : Color.secondary)
  504. .contentShape(Rectangle())
  505. .padding(.vertical)
  506. .onTapGesture {
  507. removeAlert = Alert(
  508. title: Text("Are you sure?"),
  509. message: Text("Delete preset \"\(preset.displayName)\""),
  510. primaryButton: .destructive(Text("Delete"), action: { state.removePreset(id: preset.id) }),
  511. secondaryButton: .cancel()
  512. )
  513. isRemoveAlertPresented = true
  514. }
  515. .alert(isPresented: $isRemoveAlertPresented) {
  516. removeAlert!
  517. }
  518. }
  519. if showCheckmark && isSelected {
  520. // show checkmark to indicate if the preset was actually pressed
  521. Image(systemName: "checkmark.circle.fill")
  522. .imageScale(.large)
  523. .fontWeight(.bold)
  524. .foregroundStyle(Color.green)
  525. }
  526. })
  527. }
  528. @ViewBuilder private func profilesView(for preset: OverridePresets) -> some View {
  529. let target = state.units == .mmolL ? (((preset.target ?? 0) as NSDecimalNumber) as Decimal)
  530. .asMmolL : (preset.target ?? 0) as Decimal
  531. let duration = (preset.duration ?? 0) as Decimal
  532. let name = ((preset.name ?? "") == "") || (preset.name?.isEmpty ?? true) ? "" : preset.name!
  533. let percent = preset.percentage / 100
  534. let perpetual = preset.indefinite
  535. let durationString = perpetual ? "" : "\(formatter.string(from: duration as NSNumber)!)"
  536. let scheduledSMBstring = (preset.smbIsOff && preset.smbIsAlwaysOff) ? "Scheduled SMBs" : ""
  537. let smbString = (preset.smbIsOff && scheduledSMBstring == "") ? "SMBs are off" : ""
  538. let targetString = target != 0 ? "\(glucoseFormatter.string(from: target as NSNumber)!)" : ""
  539. let maxMinutesSMB = (preset.smbMinutes as Decimal?) != nil ? (preset.smbMinutes ?? 0) as Decimal : 0
  540. let maxMinutesUAM = (preset.uamMinutes as Decimal?) != nil ? (preset.uamMinutes ?? 0) as Decimal : 0
  541. let isfString = preset.isf ? "ISF" : ""
  542. let crString = preset.cr ? "CR" : ""
  543. let dash = crString != "" ? "/" : ""
  544. let isfAndCRstring = isfString + dash + crString
  545. let isSelected = preset.id == selectedPresetID
  546. if name != "" {
  547. ZStack(alignment: .trailing, content: {
  548. HStack {
  549. VStack {
  550. HStack {
  551. Text(name)
  552. Spacer()
  553. }
  554. HStack(spacing: 5) {
  555. Text(percent.formatted(.percent.grouping(.never).rounded().precision(.fractionLength(0))))
  556. if targetString != "" {
  557. Text(targetString)
  558. Text(targetString != "" ? state.units.rawValue : "")
  559. }
  560. if durationString != "" { Text(durationString + (perpetual ? "" : "min")) }
  561. if smbString != "" { Text(smbString).foregroundColor(.secondary).font(.caption) }
  562. if scheduledSMBstring != "" { Text(scheduledSMBstring) }
  563. if preset.advancedSettings {
  564. Text(maxMinutesSMB == 0 ? "" : maxMinutesSMB.formatted() + " SMB")
  565. Text(maxMinutesUAM == 0 ? "" : maxMinutesUAM.formatted() + " UAM")
  566. Text(isfAndCRstring)
  567. }
  568. Spacer()
  569. }
  570. .padding(.top, 2)
  571. .foregroundColor(.secondary)
  572. .font(.caption)
  573. }
  574. .contentShape(Rectangle())
  575. .onTapGesture {
  576. state.selectProfile(id_: preset.id ?? "")
  577. state.hideModal()
  578. showCheckmark.toggle()
  579. selectedPresetID = preset.id
  580. // deactivate showCheckmark after 3 seconds
  581. DispatchQueue.main.asyncAfter(deadline: .now() + 3) {
  582. showCheckmark = false
  583. }
  584. }
  585. }
  586. // show checkmark to indicate if the preset was actually pressed
  587. if showCheckmark && isSelected {
  588. Image(systemName: "checkmark.circle.fill")
  589. .imageScale(.large)
  590. .fontWeight(.bold)
  591. .foregroundStyle(Color.green)
  592. }
  593. })
  594. }
  595. }
  596. private func unChanged() -> Bool {
  597. let isChanged = (
  598. state.percentageProfiles == 100 && !state.override_target && !state.smbIsOff && !state
  599. .advancedSettings
  600. ) ||
  601. (!state._indefinite && state.durationProfile == 0) || (state.override_target && state.target == 0) ||
  602. (
  603. state.percentageProfiles == 100 && !state.override_target && !state.smbIsOff && state.isf && state.cr && state
  604. .smbMinutes == state.defaultSmbMinutes && state.uamMinutes == state.defaultUamMinutes
  605. )
  606. return isChanged
  607. }
  608. private func removeProfile(at offsets: IndexSet) {
  609. for index in offsets {
  610. let language = fetchedProfiles[index]
  611. moc.delete(language)
  612. }
  613. do {
  614. try moc.save()
  615. } catch {
  616. // To do: add error
  617. }
  618. }
  619. }
  620. }