AlternativeBolusCalcRootView.swift 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545
  1. import Charts
  2. import CoreData
  3. import SwiftUI
  4. import Swinject
  5. extension Bolus {
  6. struct AlternativeBolusCalcRootView: BaseView {
  7. let resolver: Resolver
  8. let waitForSuggestion: Bool
  9. let fetch: Bool
  10. @StateObject var state: StateModel
  11. @State private var showInfo = false
  12. @State private var exceededMaxBolus = false
  13. @State private var keepForNextWiew: Bool = false
  14. @State private var calculatorDetent = PresentationDetent.medium
  15. private enum Config {
  16. static let dividerHeight: CGFloat = 2
  17. static let overlayColour: Color = .white // Currently commented out
  18. static let spacing: CGFloat = 3
  19. }
  20. @Environment(\.colorScheme) var colorScheme
  21. @FetchRequest(
  22. entity: Meals.entity(),
  23. sortDescriptors: [NSSortDescriptor(key: "createdAt", ascending: false)]
  24. ) var meal: FetchedResults<Meals>
  25. private var formatter: NumberFormatter {
  26. let formatter = NumberFormatter()
  27. formatter.numberStyle = .decimal
  28. formatter.maximumFractionDigits = 2
  29. return formatter
  30. }
  31. private var mealFormatter: NumberFormatter {
  32. let formatter = NumberFormatter()
  33. formatter.numberStyle = .decimal
  34. formatter.maximumFractionDigits = 1
  35. return formatter
  36. }
  37. private var gluoseFormatter: NumberFormatter {
  38. let formatter = NumberFormatter()
  39. formatter.numberStyle = .decimal
  40. if state.units == .mmolL {
  41. formatter.maximumFractionDigits = 1
  42. } else { formatter.maximumFractionDigits = 0 }
  43. return formatter
  44. }
  45. private var fractionDigits: Int {
  46. if state.units == .mmolL {
  47. return 1
  48. } else { return 0 }
  49. }
  50. var body: some View {
  51. Form {
  52. Section {
  53. if state.waitForSuggestion {
  54. Text("Please wait")
  55. } else {
  56. predictionChart
  57. }
  58. } header: { Text("Predictions") }
  59. Section {}
  60. if fetch {
  61. Section {
  62. mealEntries
  63. } header: { Text("Meal Summary") }
  64. }
  65. Section {
  66. HStack {
  67. Button(action: {
  68. showInfo.toggle()
  69. }, label: {
  70. Image(systemName: "info.circle")
  71. Text("Calculations")
  72. })
  73. .foregroundStyle(.blue)
  74. .font(.footnote)
  75. .buttonStyle(PlainButtonStyle())
  76. .frame(maxWidth: .infinity, alignment: .leading)
  77. if state.fattyMeals {
  78. Spacer()
  79. Toggle(isOn: $state.useFattyMealCorrectionFactor) {
  80. Text("Fatty Meal")
  81. }
  82. .toggleStyle(CheckboxToggleStyle())
  83. .font(.footnote)
  84. .onChange(of: state.useFattyMealCorrectionFactor) { _ in
  85. state.insulinCalculated = state.calculateInsulin()
  86. }
  87. }
  88. }
  89. if state.waitForSuggestion {
  90. HStack {
  91. Text("Wait please").foregroundColor(.secondary)
  92. Spacer()
  93. ActivityIndicator(isAnimating: .constant(true), style: .medium) // fix iOS 15 bug
  94. }
  95. } else {
  96. HStack {
  97. Text("Recommended Bolus")
  98. Spacer()
  99. Text(
  100. formatter
  101. .string(from: Double(state.insulinCalculated) as NSNumber) ?? ""
  102. )
  103. Text(
  104. NSLocalizedString(" U", comment: "Unit in number of units delivered (keep the space character!)")
  105. ).foregroundColor(.secondary)
  106. }.contentShape(Rectangle())
  107. .onTapGesture { state.amount = state.insulinCalculated }
  108. }
  109. HStack {
  110. Text("Bolus")
  111. Spacer()
  112. DecimalTextField(
  113. "0",
  114. value: $state.amount,
  115. formatter: formatter,
  116. autofocus: false,
  117. cleanInput: true
  118. )
  119. Text(exceededMaxBolus ? "😵" : " U").foregroundColor(.secondary)
  120. }
  121. .onChange(of: state.amount) { newValue in
  122. if newValue > state.maxBolus {
  123. exceededMaxBolus = true
  124. } else {
  125. exceededMaxBolus = false
  126. }
  127. }
  128. } header: { Text("Bolus") }
  129. if state.amount > 0 {
  130. Section {
  131. Button {
  132. keepForNextWiew = true
  133. state.add()
  134. }
  135. label: { Text(exceededMaxBolus ? "Max Bolus exceeded!" : "Enact bolus") }
  136. .frame(maxWidth: .infinity, alignment: .center)
  137. .disabled(disabled)
  138. .listRowBackground(!disabled ? Color(.systemBlue) : Color(.systemGray4))
  139. .tint(.white)
  140. }
  141. }
  142. if state.amount <= 0 {
  143. Section {
  144. Button {
  145. keepForNextWiew = true
  146. state.showModal(for: nil)
  147. }
  148. label: { Text("Continue without bolus") }.frame(maxWidth: .infinity, alignment: .center)
  149. }
  150. }
  151. }
  152. .blur(radius: showInfo ? 3 : 0)
  153. .navigationTitle("Enact Bolus")
  154. .navigationBarTitleDisplayMode(.inline)
  155. .navigationBarItems(
  156. leading: Button {
  157. carbsView()
  158. }
  159. label: {
  160. HStack {
  161. Image(systemName: "chevron.backward")
  162. Text("Meal")
  163. }
  164. },
  165. trailing: Button { state.hideModal() }
  166. label: { Text("Close") }
  167. )
  168. .onAppear {
  169. configureView {
  170. state.waitForSuggestionInitial = waitForSuggestion
  171. state.waitForSuggestion = waitForSuggestion
  172. state.insulinCalculated = state.calculateInsulin()
  173. }
  174. }
  175. .onDisappear {
  176. if fetch, hasFatOrProtein, !keepForNextWiew, state.useCalc {
  177. state.delete(deleteTwice: true, meal: meal)
  178. } else if fetch, !keepForNextWiew, state.useCalc {
  179. state.delete(deleteTwice: false, meal: meal)
  180. }
  181. }
  182. .sheet(isPresented: $showInfo) {
  183. bolusInfoAlternativeCalculator
  184. .presentationDetents(
  185. [fetch ? .fraction(0.75) : .fraction(0.60), .large],
  186. selection: $calculatorDetent
  187. )
  188. }
  189. }
  190. var predictionChart: some View {
  191. ZStack {
  192. PredictionView(
  193. predictions: $state.predictions, units: $state.units, eventualBG: $state.evBG, target: $state.target,
  194. displayPredictions: $state.displayPredictions
  195. )
  196. }
  197. }
  198. // Pop-up
  199. var bolusInfoAlternativeCalculator: some View {
  200. NavigationStack {
  201. VStack {
  202. VStack {
  203. VStack(spacing: Config.spacing) {
  204. if fetch {
  205. mealEntries.padding()
  206. Divider().frame(height: Config.dividerHeight) // .overlay(Config.overlayColour)
  207. }
  208. settings.padding()
  209. }
  210. Divider().frame(height: Config.dividerHeight) // .overlay(Config.overlayColour)
  211. insulinParts.padding()
  212. Divider().frame(height: Config.dividerHeight) // .overlay(Config.overlayColour)
  213. VStack {
  214. HStack {
  215. Text("Full Bolus")
  216. .foregroundColor(.secondary)
  217. Spacer()
  218. let insulin = state.roundedWholeCalc
  219. Text(insulin.formatted())
  220. .foregroundStyle(state.roundedWholeCalc < 0 ? Color.loopRed : Color.primary)
  221. Text(" U")
  222. .foregroundColor(.secondary)
  223. }
  224. }.padding(.horizontal)
  225. Divider().frame(height: Config.dividerHeight)
  226. results.padding()
  227. if exceededMaxBolus {
  228. Divider().frame(height: Config.dividerHeight) // .overlay(Config.overlayColour)
  229. HStack {
  230. let maxBolus = state.maxBolus
  231. let maxBolusFormatted = maxBolus.formatted()
  232. Text("Your entered amount was limited by your max Bolus setting of \(maxBolusFormatted)\(" U")")
  233. }
  234. .padding()
  235. .fontWeight(.semibold)
  236. .foregroundStyle(Color.loopRed)
  237. }
  238. }
  239. Spacer()
  240. }
  241. .navigationTitle("Calculations")
  242. .navigationBarTitleDisplayMode(.inline)
  243. .toolbar {
  244. ToolbarItem(placement: .navigationBarTrailing) {
  245. Button("Close", action: { showInfo = false })
  246. }
  247. }
  248. }
  249. }
  250. private var disabled: Bool {
  251. state.amount <= 0 || state.amount > state.maxBolus
  252. }
  253. var changed: Bool {
  254. ((meal.first?.carbs ?? 0) > 0) || ((meal.first?.fat ?? 0) > 0) || ((meal.first?.protein ?? 0) > 0)
  255. }
  256. var hasFatOrProtein: Bool {
  257. ((meal.first?.fat ?? 0) > 0) || ((meal.first?.protein ?? 0) > 0)
  258. }
  259. func carbsView() {
  260. if fetch {
  261. keepForNextWiew = true
  262. state.backToCarbsView(complexEntry: true, meal, override: false)
  263. } else {
  264. state.backToCarbsView(complexEntry: false, meal, override: true)
  265. }
  266. }
  267. var mealEntries: some View {
  268. VStack {
  269. if let carbs = meal.first?.carbs, carbs > 0 {
  270. HStack {
  271. Text("Carbs").foregroundColor(.secondary)
  272. Spacer()
  273. Text(carbs.formatted())
  274. Text("g").foregroundColor(.secondary)
  275. }
  276. }
  277. if let fat = meal.first?.fat, fat > 0 {
  278. HStack {
  279. Text("Fat").foregroundColor(.secondary)
  280. Spacer()
  281. Text(fat.formatted())
  282. Text("g").foregroundColor(.secondary)
  283. }
  284. }
  285. if let protein = meal.first?.protein, protein > 0 {
  286. HStack {
  287. Text("Protein").foregroundColor(.secondary)
  288. Spacer()
  289. Text(protein.formatted())
  290. Text("g").foregroundColor(.secondary)
  291. }
  292. }
  293. if let note = meal.first?.note, note != "" {
  294. HStack {
  295. Text("Note").foregroundColor(.secondary)
  296. Spacer()
  297. Text(note).foregroundColor(.secondary)
  298. }
  299. }
  300. }
  301. }
  302. var settings: some View {
  303. VStack {
  304. HStack {
  305. Text("Carb Ratio")
  306. .foregroundColor(.secondary)
  307. .frame(minWidth: 115, alignment: .leading)
  308. Text(state.carbRatio.formatted())
  309. .frame(minWidth: 40, alignment: .trailing)
  310. Text(NSLocalizedString("g/U", comment: " grams per Unit"))
  311. .foregroundColor(.secondary)
  312. .frame(minWidth: 70, alignment: .leading)
  313. Spacer()
  314. }
  315. HStack {
  316. Text("ISF")
  317. .foregroundColor(.secondary)
  318. .frame(minWidth: 115, alignment: .leading)
  319. let isf = state.isf
  320. Text(isf.formatted())
  321. .frame(minWidth: 40, alignment: .trailing)
  322. Text(state.units.rawValue + NSLocalizedString("/U", comment: "/Insulin unit"))
  323. .foregroundColor(.secondary)
  324. .frame(minWidth: 70, alignment: .leading)
  325. Spacer()
  326. }
  327. HStack {
  328. Text("Target Glucose")
  329. .foregroundColor(.secondary)
  330. .frame(minWidth: 115, alignment: .leading)
  331. let target = state.units == .mmolL ? state.target.asMmolL : state.target
  332. Text(
  333. target
  334. .formatted(.number.grouping(.never).rounded().precision(.fractionLength(fractionDigits)))
  335. ).frame(minWidth: 40, alignment: .trailing)
  336. Text(state.units.rawValue)
  337. .foregroundColor(.secondary)
  338. .frame(minWidth: 70, alignment: .leading)
  339. Spacer()
  340. }
  341. HStack {
  342. Text("Basal")
  343. .foregroundColor(.secondary)
  344. .frame(minWidth: 115, alignment: .leading)
  345. let basal = state.basal
  346. Text(basal.formatted())
  347. .frame(minWidth: 40, alignment: .trailing)
  348. Text(NSLocalizedString("U/h", comment: " Units per hour"))
  349. .foregroundColor(.secondary)
  350. .frame(minWidth: 70, alignment: .leading)
  351. Spacer()
  352. }
  353. HStack {
  354. Text("Fraction")
  355. .foregroundColor(.secondary)
  356. .frame(minWidth: 115, alignment: .leading)
  357. let fraction = state.fraction
  358. Text(fraction.formatted())
  359. .frame(minWidth: 40, alignment: .trailing)
  360. Text("").frame(minWidth: 70, alignment: .leading)
  361. Spacer()
  362. }
  363. if state.useFattyMealCorrectionFactor {
  364. HStack {
  365. Text("Fatty Meal Factor")
  366. .foregroundColor(.orange)
  367. .frame(minWidth: 115, alignment: .leading)
  368. let fraction = state.fattyMealFactor
  369. Text(fraction.formatted())
  370. foregroundColor(.orange)
  371. .frame(minWidth: 40, alignment: .trailing)
  372. Text("").frame(minWidth: 70, alignment: .leading)
  373. Spacer()
  374. }
  375. }
  376. }
  377. }
  378. var insulinParts: some View {
  379. VStack(spacing: Config.spacing) {
  380. HStack(alignment: .center, spacing: nil) {
  381. Text("Glucose")
  382. .foregroundColor(.secondary)
  383. .frame(minWidth: 115, alignment: .leading)
  384. let glucose = state.units == .mmolL ? state.currentBG.asMmolL : state.currentBG
  385. Text(glucose.formatted(.number.grouping(.never).rounded().precision(.fractionLength(fractionDigits))))
  386. .frame(minWidth: 40, alignment: .trailing)
  387. Text(state.units.rawValue)
  388. .foregroundColor(.secondary)
  389. .frame(minWidth: 70, alignment: .leading)
  390. Image(systemName: "arrow.right")
  391. .frame(minWidth: 20, alignment: .trailing)
  392. Spacer()
  393. let targetDifferenceInsulin = state.targetDifferenceInsulin
  394. // rounding
  395. let targetDifferenceInsulinAsDouble = NSDecimalNumber(decimal: targetDifferenceInsulin).doubleValue
  396. let roundedTargetDifferenceInsulin = Decimal(round(100 * targetDifferenceInsulinAsDouble) / 100)
  397. Text(roundedTargetDifferenceInsulin.formatted())
  398. Text(" U")
  399. .foregroundColor(.secondary)
  400. }
  401. HStack(alignment: .center, spacing: nil) {
  402. Text("IOB")
  403. .foregroundColor(.secondary)
  404. .frame(minWidth: 115, alignment: .leading)
  405. let iob = state.iob
  406. // rounding
  407. let iobAsDouble = NSDecimalNumber(decimal: iob).doubleValue
  408. let roundedIob = Decimal(round(100 * iobAsDouble) / 100)
  409. Text(roundedIob.formatted())
  410. .frame(minWidth: 40, alignment: .trailing)
  411. Text("U")
  412. .foregroundColor(.secondary)
  413. .frame(minWidth: 70, alignment: .leading)
  414. Image(systemName: "arrow.right")
  415. .frame(minWidth: 20, alignment: .trailing)
  416. Spacer()
  417. let iobCalc = state.iobInsulinReduction
  418. // rounding
  419. let iobCalcAsDouble = NSDecimalNumber(decimal: iobCalc).doubleValue
  420. let roundedIobCalc = Decimal(round(100 * iobCalcAsDouble) / 100)
  421. Text(roundedIobCalc.formatted())
  422. Text(" U").foregroundColor(.secondary)
  423. }
  424. HStack(alignment: .center, spacing: nil) {
  425. Text("Trend")
  426. .foregroundColor(.secondary)
  427. .frame(minWidth: 115, alignment: .leading)
  428. let trend = state.units == .mmolL ? state.deltaBG.asMmolL : state.deltaBG
  429. Text(trend.formatted(.number.grouping(.never).rounded().precision(.fractionLength(fractionDigits))))
  430. .frame(minWidth: 40, alignment: .trailing)
  431. Text(state.units.rawValue).foregroundColor(.secondary)
  432. .frame(minWidth: 70, alignment: .leading)
  433. Image(systemName: "arrow.right")
  434. .frame(minWidth: 20, alignment: .trailing)
  435. Spacer()
  436. let trendInsulin = state.fifteenMinInsulin
  437. // rounding
  438. let trendInsulinAsDouble = NSDecimalNumber(decimal: trendInsulin).doubleValue
  439. let roundedTrendInsulin = Decimal(round(100 * trendInsulinAsDouble) / 100)
  440. Text(roundedTrendInsulin.formatted())
  441. Text(" U")
  442. .foregroundColor(.secondary)
  443. }
  444. HStack(alignment: .center, spacing: nil) {
  445. Text("COB")
  446. .foregroundColor(.secondary)
  447. .frame(minWidth: 115, alignment: .leading)
  448. let cob = state.cob
  449. Text(cob.formatted())
  450. .frame(minWidth: 40, alignment: .trailing)
  451. let unitGrams = NSLocalizedString("g", comment: "grams")
  452. Text(unitGrams).foregroundColor(.secondary)
  453. .frame(minWidth: 70, alignment: .leading)
  454. Image(systemName: "arrow.right")
  455. .frame(minWidth: 20, alignment: .trailing)
  456. Spacer()
  457. let insulinCob = state.wholeCobInsulin
  458. // rounding
  459. let insulinCobAsDouble = NSDecimalNumber(decimal: insulinCob).doubleValue
  460. let roundedInsulinCob = Decimal(round(100 * insulinCobAsDouble) / 100)
  461. Text(roundedInsulinCob.formatted())
  462. Text(" U")
  463. .foregroundColor(.secondary)
  464. }
  465. }
  466. }
  467. var results: some View {
  468. VStack {
  469. HStack {
  470. Text("Result")
  471. .fontWeight(.bold)
  472. Spacer()
  473. let fraction = state.fraction
  474. Text(fraction.formatted())
  475. Text(" x ")
  476. .foregroundColor(.secondary)
  477. // if fatty meal is chosen
  478. if state.useFattyMealCorrectionFactor {
  479. let fattyMealFactor = state.fattyMealFactor
  480. Text(fattyMealFactor.formatted())
  481. .foregroundColor(.orange)
  482. Text(" x ")
  483. .foregroundColor(.secondary)
  484. }
  485. let insulin = state.roundedWholeCalc
  486. Text(insulin.formatted()).foregroundStyle(state.roundedWholeCalc < 0 ? Color.loopRed : Color.primary)
  487. Text(" U")
  488. .foregroundColor(.secondary)
  489. Text(" = ")
  490. .foregroundColor(.secondary)
  491. let result = state.insulinCalculated
  492. // rounding
  493. let resultAsDouble = NSDecimalNumber(decimal: result).doubleValue
  494. let roundedResult = Decimal(round(100 * resultAsDouble) / 100)
  495. Text(roundedResult.formatted())
  496. .fontWeight(.bold)
  497. .font(.system(size: 16))
  498. .foregroundColor(.blue)
  499. Text(" U")
  500. .foregroundColor(.secondary)
  501. }
  502. }
  503. }
  504. }
  505. }