OverrideProfilesRootView.swift 26 KB

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