OverrideProfilesRootView.swift 28 KB

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