AlternativeBolusCalcRootView.swift 24 KB

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