AlternativeBolusCalcRootView.swift 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567
  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, id: meal.first?.id ?? "")
  194. } else if fetch, !keepForNextWiew, state.useCalc {
  195. state.delete(deleteTwice: false, id: meal.first?.id ?? "")
  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. let id_ = meal.first?.id ?? ""
  283. if fetch {
  284. keepForNextWiew = true
  285. state.backToCarbsView(complexEntry: fetch, id_, override: false)
  286. } else {
  287. state.backToCarbsView(complexEntry: false, id_, override: true)
  288. }
  289. }
  290. var mealEntries: some View {
  291. VStack {
  292. if let carbs = meal.first?.carbs, carbs > 0 {
  293. HStack {
  294. Text("Carbs")
  295. Spacer()
  296. Text(carbs.formatted())
  297. Text("g")
  298. }.foregroundColor(.secondary)
  299. }
  300. if let fat = meal.first?.fat, fat > 0 {
  301. HStack {
  302. Text("Fat")
  303. Spacer()
  304. Text(fat.formatted())
  305. Text("g")
  306. }.foregroundColor(.secondary)
  307. }
  308. if let protein = meal.first?.protein, protein > 0 {
  309. HStack {
  310. Text("Protein")
  311. Spacer()
  312. Text(protein.formatted())
  313. Text("g")
  314. }.foregroundColor(.secondary)
  315. }
  316. if let note = meal.first?.note, note != "" {
  317. HStack {
  318. Text("Note")
  319. Spacer()
  320. Text(note)
  321. }.foregroundColor(.secondary)
  322. }
  323. }
  324. }
  325. var settings: some View {
  326. VStack {
  327. HStack {
  328. Text("Carb Ratio")
  329. .foregroundColor(.secondary)
  330. Spacer()
  331. Text(state.carbRatio.formatted())
  332. Text(NSLocalizedString(" g/U", comment: " grams per Unit"))
  333. .foregroundColor(.secondary)
  334. }
  335. HStack {
  336. Text("ISF")
  337. .foregroundColor(.secondary)
  338. Spacer()
  339. let isf = state.isf
  340. Text(isf.formatted())
  341. Text(state.units.rawValue + NSLocalizedString("/U", comment: "/Insulin unit"))
  342. .foregroundColor(.secondary)
  343. }
  344. HStack {
  345. Text("Target Glucose")
  346. .foregroundColor(.secondary)
  347. Spacer()
  348. let target = state.units == .mmolL ? state.target.asMmolL : state.target
  349. Text(
  350. target
  351. .formatted(.number.grouping(.never).rounded().precision(.fractionLength(fractionDigits)))
  352. )
  353. Text(state.units.rawValue)
  354. .foregroundColor(.secondary)
  355. }
  356. HStack {
  357. Text("Basal")
  358. .foregroundColor(.secondary)
  359. Spacer()
  360. let basal = state.basal
  361. Text(basal.formatted())
  362. Text(NSLocalizedString(" U/h", comment: " Units per hour"))
  363. .foregroundColor(.secondary)
  364. }
  365. HStack {
  366. Text("Fraction")
  367. .foregroundColor(.secondary)
  368. Spacer()
  369. let fraction = state.fraction
  370. Text(fraction.formatted())
  371. }
  372. if state.useFattyMealCorrectionFactor {
  373. HStack {
  374. Text("Fatty Meal Factor")
  375. .foregroundColor(.orange)
  376. Spacer()
  377. let fraction = state.fattyMealFactor
  378. Text(fraction.formatted())
  379. .foregroundColor(.orange)
  380. }
  381. }
  382. if state.useSuperBolus {
  383. HStack {
  384. Text("Super Bolus")
  385. .foregroundColor(.red)
  386. Spacer()
  387. let superBolusInsulin = state.superBolusInsulin
  388. Text(superBolusInsulin.formatted()).foregroundColor(.red)
  389. Text(" U")
  390. .foregroundColor(.secondary)
  391. }
  392. }
  393. }
  394. }
  395. var insulinParts: some View {
  396. VStack(spacing: Config.spacing) {
  397. HStack {
  398. Text("Glucose")
  399. .foregroundColor(.secondary)
  400. Spacer()
  401. let glucose = state.units == .mmolL ? state.currentBG.asMmolL : state.currentBG
  402. Text(glucose.formatted(.number.grouping(.never).rounded().precision(.fractionLength(fractionDigits))))
  403. Text(state.units.rawValue)
  404. .foregroundColor(.secondary)
  405. Spacer()
  406. Image(systemName: "arrow.right")
  407. Spacer()
  408. let targetDifferenceInsulin = state.targetDifferenceInsulin
  409. // rounding
  410. let targetDifferenceInsulinAsDouble = NSDecimalNumber(decimal: targetDifferenceInsulin).doubleValue
  411. let roundedTargetDifferenceInsulin = Decimal(round(100 * targetDifferenceInsulinAsDouble) / 100)
  412. Text(roundedTargetDifferenceInsulin.formatted())
  413. Text(" U")
  414. .foregroundColor(.secondary)
  415. }
  416. HStack {
  417. Text("IOB")
  418. .foregroundColor(.secondary)
  419. Spacer()
  420. let iob = state.iob
  421. // rounding
  422. let iobAsDouble = NSDecimalNumber(decimal: iob).doubleValue
  423. let roundedIob = Decimal(round(100 * iobAsDouble) / 100)
  424. Text(roundedIob.formatted())
  425. Text(" U")
  426. .foregroundColor(.secondary)
  427. Spacer()
  428. Image(systemName: "arrow.right")
  429. Spacer()
  430. let iobCalc = state.iobInsulinReduction
  431. // rounding
  432. let iobCalcAsDouble = NSDecimalNumber(decimal: iobCalc).doubleValue
  433. let roundedIobCalc = Decimal(round(100 * iobCalcAsDouble) / 100)
  434. Text(roundedIobCalc.formatted())
  435. Text(" U").foregroundColor(.secondary)
  436. }
  437. HStack {
  438. Text("Trend")
  439. .foregroundColor(.secondary)
  440. Spacer()
  441. let trend = state.units == .mmolL ? state.deltaBG.asMmolL : state.deltaBG
  442. Text(trend.formatted(.number.grouping(.never).rounded().precision(.fractionLength(fractionDigits))))
  443. Text(state.units.rawValue).foregroundColor(.secondary)
  444. Spacer()
  445. Image(systemName: "arrow.right")
  446. Spacer()
  447. let trendInsulin = state.fifteenMinInsulin
  448. // rounding
  449. let trendInsulinAsDouble = NSDecimalNumber(decimal: trendInsulin).doubleValue
  450. let roundedTrendInsulin = Decimal(round(100 * trendInsulinAsDouble) / 100)
  451. Text(roundedTrendInsulin.formatted())
  452. Text(" U")
  453. .foregroundColor(.secondary)
  454. }
  455. HStack {
  456. Text("COB")
  457. .foregroundColor(.secondary)
  458. Spacer()
  459. let cob = state.cob
  460. Text(cob.formatted())
  461. let unitGrams = NSLocalizedString(" g", comment: "grams")
  462. Text(unitGrams).foregroundColor(.secondary)
  463. Spacer()
  464. Image(systemName: "arrow.right")
  465. Spacer()
  466. let insulinCob = state.wholeCobInsulin
  467. // rounding
  468. let insulinCobAsDouble = NSDecimalNumber(decimal: insulinCob).doubleValue
  469. let roundedInsulinCob = Decimal(round(100 * insulinCobAsDouble) / 100)
  470. Text(roundedInsulinCob.formatted())
  471. Text(" U")
  472. .foregroundColor(.secondary)
  473. }
  474. }
  475. }
  476. var results: some View {
  477. VStack {
  478. HStack {
  479. Text("Result")
  480. .fontWeight(.bold)
  481. Spacer()
  482. if !state.useSuperBolus {
  483. let fraction = state.fraction
  484. Text(fraction.formatted())
  485. Text(" x ")
  486. .foregroundColor(.secondary)
  487. // if fatty meal is chosen
  488. if state.useFattyMealCorrectionFactor {
  489. let fattyMealFactor = state.fattyMealFactor
  490. Text(fattyMealFactor.formatted())
  491. .foregroundColor(.orange)
  492. Text(" x ")
  493. .foregroundColor(.secondary)
  494. }
  495. let insulin = state.roundedWholeCalc
  496. Text(insulin.formatted()).foregroundStyle(state.roundedWholeCalc < 0 ? Color.loopRed : Color.primary)
  497. Text(" U")
  498. .foregroundColor(.secondary)
  499. } else {
  500. // roundedWholeCalc
  501. let insulin = state.roundedWholeCalc
  502. Text(insulin.formatted()).foregroundStyle(state.roundedWholeCalc < 0 ? Color.loopRed : Color.primary)
  503. Text(" U")
  504. // plus
  505. Text(" + ")
  506. .foregroundColor(.secondary)
  507. // superBolusInsulin
  508. let superBolusInsulin = state.superBolusInsulin
  509. Text(superBolusInsulin.formatted()).foregroundColor(.red)
  510. Text(" U")
  511. .foregroundColor(.secondary)
  512. }
  513. Text(" = ")
  514. .foregroundColor(.secondary)
  515. let result = state.insulinCalculated
  516. // rounding
  517. let resultAsDouble = NSDecimalNumber(decimal: result).doubleValue
  518. let roundedResult = Decimal(round(100 * resultAsDouble) / 100)
  519. Text(roundedResult.formatted())
  520. .fontWeight(.bold)
  521. .font(.system(size: 16))
  522. .foregroundColor(.blue)
  523. Text(" U")
  524. .foregroundColor(.secondary)
  525. }
  526. }
  527. }
  528. }
  529. }