AlternativeBolusCalcRootView.swift 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566
  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. }
  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. var predictionChart: some View {
  203. ZStack {
  204. PredictionView(
  205. predictions: $state.predictions, units: $state.units, eventualBG: $state.evBG, target: $state.target,
  206. displayPredictions: $state.displayPredictions
  207. )
  208. }
  209. }
  210. // Pop-up
  211. var bolusInfoAlternativeCalculator: some View {
  212. VStack {
  213. VStack {
  214. VStack(spacing: Config.spacing) {
  215. HStack {
  216. Text("Calculations")
  217. .font(.title3).frame(maxWidth: .infinity, alignment: .center)
  218. }.padding(10)
  219. if fetch {
  220. mealEntries.padding()
  221. Divider().frame(height: Config.dividerHeight) // .overlay(Config.overlayColour)
  222. }
  223. settings.padding()
  224. }
  225. Divider().frame(height: Config.dividerHeight) // .overlay(Config.overlayColour)
  226. insulinParts.padding()
  227. Divider().frame(height: Config.dividerHeight) // .overlay(Config.overlayColour)
  228. VStack {
  229. HStack {
  230. Text("Full Bolus")
  231. .foregroundColor(.secondary)
  232. Spacer()
  233. let insulin = state.roundedWholeCalc
  234. Text(insulin.formatted()).foregroundStyle(state.roundedWholeCalc < 0 ? Color.loopRed : Color.primary)
  235. Text(" U")
  236. .foregroundColor(.secondary)
  237. }
  238. }.padding(.horizontal)
  239. Divider().frame(height: Config.dividerHeight)
  240. results.padding()
  241. Divider().frame(height: Config.dividerHeight) // .overlay(Config.overlayColour)
  242. if exceededMaxBolus {
  243. HStack {
  244. let maxBolus = state.maxBolus
  245. let maxBolusFormatted = maxBolus.formatted()
  246. Text("Your entered amount was limited by your max Bolus setting of \(maxBolusFormatted)\(" U")")
  247. }
  248. .padding()
  249. .fontWeight(.semibold)
  250. .foregroundStyle(Color.loopRed)
  251. }
  252. }
  253. .padding(.top, 10)
  254. .padding(.bottom, 15)
  255. // Hide pop-up
  256. VStack {
  257. Button { showInfo = false }
  258. label: { Text("OK") }
  259. .frame(maxWidth: .infinity, alignment: .center)
  260. .font(.system(size: 16))
  261. .fontWeight(.semibold)
  262. .foregroundColor(.blue)
  263. }
  264. .padding(.bottom, 20)
  265. }
  266. .font(.footnote)
  267. .background(
  268. RoundedRectangle(cornerRadius: 10, style: .continuous)
  269. .fill(Color(colorScheme == .dark ? UIColor.systemGray4 : UIColor.systemGray4).opacity(0.9))
  270. )
  271. }
  272. private var disabled: Bool {
  273. state.amount <= 0 || state.amount > state.maxBolus
  274. }
  275. var changed: Bool {
  276. ((meal.first?.carbs ?? 0) > 0) || ((meal.first?.fat ?? 0) > 0) || ((meal.first?.protein ?? 0) > 0)
  277. }
  278. var hasFatOrProtein: Bool {
  279. ((meal.first?.fat ?? 0) > 0) || ((meal.first?.protein ?? 0) > 0)
  280. }
  281. func carbsView() {
  282. if fetch {
  283. keepForNextWiew = true
  284. state.backToCarbsView(complexEntry: true, meal, override: false)
  285. } else {
  286. state.backToCarbsView(complexEntry: false, meal, override: true)
  287. }
  288. }
  289. var mealEntries: some View {
  290. VStack {
  291. if let carbs = meal.first?.carbs, carbs > 0 {
  292. HStack {
  293. Text("Carbs")
  294. Spacer()
  295. Text(carbs.formatted())
  296. Text("g")
  297. }.foregroundColor(.secondary)
  298. }
  299. if let fat = meal.first?.fat, fat > 0 {
  300. HStack {
  301. Text("Fat")
  302. Spacer()
  303. Text(fat.formatted())
  304. Text("g")
  305. }.foregroundColor(.secondary)
  306. }
  307. if let protein = meal.first?.protein, protein > 0 {
  308. HStack {
  309. Text("Protein")
  310. Spacer()
  311. Text(protein.formatted())
  312. Text("g")
  313. }.foregroundColor(.secondary)
  314. }
  315. if let note = meal.first?.note, note != "" {
  316. HStack {
  317. Text("Note")
  318. Spacer()
  319. Text(note)
  320. }.foregroundColor(.secondary)
  321. }
  322. }
  323. }
  324. var settings: some View {
  325. VStack {
  326. HStack {
  327. Text("Carb Ratio")
  328. .foregroundColor(.secondary)
  329. Spacer()
  330. Text(state.carbRatio.formatted())
  331. Text(NSLocalizedString(" g/U", comment: " grams per Unit"))
  332. .foregroundColor(.secondary)
  333. }
  334. HStack {
  335. Text("ISF")
  336. .foregroundColor(.secondary)
  337. Spacer()
  338. let isf = state.isf
  339. Text(isf.formatted())
  340. Text(state.units.rawValue + NSLocalizedString("/U", comment: "/Insulin unit"))
  341. .foregroundColor(.secondary)
  342. }
  343. HStack {
  344. Text("Target Glucose")
  345. .foregroundColor(.secondary)
  346. Spacer()
  347. let target = state.units == .mmolL ? state.target.asMmolL : state.target
  348. Text(
  349. target
  350. .formatted(.number.grouping(.never).rounded().precision(.fractionLength(fractionDigits)))
  351. )
  352. Text(state.units.rawValue)
  353. .foregroundColor(.secondary)
  354. }
  355. HStack {
  356. Text("Basal")
  357. .foregroundColor(.secondary)
  358. Spacer()
  359. let basal = state.basal
  360. Text(basal.formatted())
  361. Text(NSLocalizedString(" U/h", comment: " Units per hour"))
  362. .foregroundColor(.secondary)
  363. }
  364. HStack {
  365. Text("Fraction")
  366. .foregroundColor(.secondary)
  367. Spacer()
  368. let fraction = state.fraction
  369. Text(fraction.formatted())
  370. }
  371. if state.useFattyMealCorrectionFactor {
  372. HStack {
  373. Text("Fatty Meal Factor")
  374. .foregroundColor(.orange)
  375. Spacer()
  376. let fraction = state.fattyMealFactor
  377. Text(fraction.formatted())
  378. .foregroundColor(.orange)
  379. }
  380. }
  381. if state.useSuperBolus {
  382. HStack {
  383. Text("Super Bolus")
  384. .foregroundColor(.red)
  385. Spacer()
  386. let superBolusInsulin = state.superBolusInsulin
  387. Text(superBolusInsulin.formatted()).foregroundColor(.red)
  388. Text(" U")
  389. .foregroundColor(.secondary)
  390. }
  391. }
  392. }
  393. }
  394. var insulinParts: some View {
  395. VStack(spacing: Config.spacing) {
  396. HStack {
  397. Text("Glucose")
  398. .foregroundColor(.secondary)
  399. Spacer()
  400. let glucose = state.units == .mmolL ? state.currentBG.asMmolL : state.currentBG
  401. Text(glucose.formatted(.number.grouping(.never).rounded().precision(.fractionLength(fractionDigits))))
  402. Text(state.units.rawValue)
  403. .foregroundColor(.secondary)
  404. Spacer()
  405. Image(systemName: "arrow.right")
  406. Spacer()
  407. let targetDifferenceInsulin = state.targetDifferenceInsulin
  408. // rounding
  409. let targetDifferenceInsulinAsDouble = NSDecimalNumber(decimal: targetDifferenceInsulin).doubleValue
  410. let roundedTargetDifferenceInsulin = Decimal(round(100 * targetDifferenceInsulinAsDouble) / 100)
  411. Text(roundedTargetDifferenceInsulin.formatted())
  412. Text(" U")
  413. .foregroundColor(.secondary)
  414. }
  415. HStack {
  416. Text("IOB")
  417. .foregroundColor(.secondary)
  418. Spacer()
  419. let iob = state.iob
  420. // rounding
  421. let iobAsDouble = NSDecimalNumber(decimal: iob).doubleValue
  422. let roundedIob = Decimal(round(100 * iobAsDouble) / 100)
  423. Text(roundedIob.formatted())
  424. Text(" U")
  425. .foregroundColor(.secondary)
  426. Spacer()
  427. Image(systemName: "arrow.right")
  428. Spacer()
  429. let iobCalc = state.iobInsulinReduction
  430. // rounding
  431. let iobCalcAsDouble = NSDecimalNumber(decimal: iobCalc).doubleValue
  432. let roundedIobCalc = Decimal(round(100 * iobCalcAsDouble) / 100)
  433. Text(roundedIobCalc.formatted())
  434. Text(" U").foregroundColor(.secondary)
  435. }
  436. HStack {
  437. Text("Trend")
  438. .foregroundColor(.secondary)
  439. Spacer()
  440. let trend = state.units == .mmolL ? state.deltaBG.asMmolL : state.deltaBG
  441. Text(trend.formatted(.number.grouping(.never).rounded().precision(.fractionLength(fractionDigits))))
  442. Text(state.units.rawValue).foregroundColor(.secondary)
  443. Spacer()
  444. Image(systemName: "arrow.right")
  445. Spacer()
  446. let trendInsulin = state.fifteenMinInsulin
  447. // rounding
  448. let trendInsulinAsDouble = NSDecimalNumber(decimal: trendInsulin).doubleValue
  449. let roundedTrendInsulin = Decimal(round(100 * trendInsulinAsDouble) / 100)
  450. Text(roundedTrendInsulin.formatted())
  451. Text(" U")
  452. .foregroundColor(.secondary)
  453. }
  454. HStack {
  455. Text("COB")
  456. .foregroundColor(.secondary)
  457. Spacer()
  458. let cob = state.cob
  459. Text(cob.formatted())
  460. let unitGrams = NSLocalizedString(" g", comment: "grams")
  461. Text(unitGrams).foregroundColor(.secondary)
  462. Spacer()
  463. Image(systemName: "arrow.right")
  464. Spacer()
  465. let insulinCob = state.wholeCobInsulin
  466. // rounding
  467. let insulinCobAsDouble = NSDecimalNumber(decimal: insulinCob).doubleValue
  468. let roundedInsulinCob = Decimal(round(100 * insulinCobAsDouble) / 100)
  469. Text(roundedInsulinCob.formatted())
  470. Text(" U")
  471. .foregroundColor(.secondary)
  472. }
  473. }
  474. }
  475. var results: some View {
  476. VStack {
  477. HStack {
  478. Text("Result")
  479. .fontWeight(.bold)
  480. Spacer()
  481. if !state.useSuperBolus {
  482. let fraction = state.fraction
  483. Text(fraction.formatted())
  484. Text(" x ")
  485. .foregroundColor(.secondary)
  486. // if fatty meal is chosen
  487. if state.useFattyMealCorrectionFactor {
  488. let fattyMealFactor = state.fattyMealFactor
  489. Text(fattyMealFactor.formatted())
  490. .foregroundColor(.orange)
  491. Text(" x ")
  492. .foregroundColor(.secondary)
  493. }
  494. let insulin = state.roundedWholeCalc
  495. Text(insulin.formatted()).foregroundStyle(state.roundedWholeCalc < 0 ? Color.loopRed : Color.primary)
  496. Text(" U")
  497. .foregroundColor(.secondary)
  498. } else {
  499. // roundedWholeCalc
  500. let insulin = state.roundedWholeCalc
  501. Text(insulin.formatted()).foregroundStyle(state.roundedWholeCalc < 0 ? Color.loopRed : Color.primary)
  502. Text(" U")
  503. // plus
  504. Text(" + ")
  505. .foregroundColor(.secondary)
  506. // superBolusInsulin
  507. let superBolusInsulin = state.superBolusInsulin
  508. Text(superBolusInsulin.formatted()).foregroundColor(.red)
  509. Text(" U")
  510. .foregroundColor(.secondary)
  511. }
  512. Text(" = ")
  513. .foregroundColor(.secondary)
  514. let result = state.insulinCalculated
  515. // rounding
  516. let resultAsDouble = NSDecimalNumber(decimal: result).doubleValue
  517. let roundedResult = Decimal(round(100 * resultAsDouble) / 100)
  518. Text(roundedResult.formatted())
  519. .fontWeight(.bold)
  520. .font(.system(size: 16))
  521. .foregroundColor(.blue)
  522. Text(" U")
  523. .foregroundColor(.secondary)
  524. }
  525. }
  526. }
  527. }
  528. }