AlternativeBolusCalcRootView.swift 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523
  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. }
  86. }
  87. }
  88. if state.waitForSuggestion {
  89. HStack {
  90. Text("Wait please").foregroundColor(.secondary)
  91. Spacer()
  92. ActivityIndicator(isAnimating: .constant(true), style: .medium) // fix iOS 15 bug
  93. }
  94. } else {
  95. HStack {
  96. Text("Recommended Bolus")
  97. Spacer()
  98. Text(
  99. formatter
  100. .string(from: Double(state.insulinCalculated) as NSNumber) ?? ""
  101. )
  102. Text(
  103. NSLocalizedString(" U", comment: "Unit in number of units delivered (keep the space character!)")
  104. ).foregroundColor(.secondary)
  105. }.contentShape(Rectangle())
  106. .onTapGesture { state.amount = state.insulinCalculated }
  107. }
  108. HStack {
  109. Text("Bolus")
  110. Spacer()
  111. DecimalTextField(
  112. "0",
  113. value: $state.amount,
  114. formatter: formatter,
  115. autofocus: false,
  116. cleanInput: true
  117. )
  118. Text(exceededMaxBolus ? "😵" : " U").foregroundColor(.secondary)
  119. }
  120. .onChange(of: state.amount) { newValue in
  121. if newValue > state.maxBolus {
  122. exceededMaxBolus = true
  123. } else {
  124. exceededMaxBolus = false
  125. }
  126. }
  127. } header: { Text("Bolus") }
  128. if state.amount > 0 {
  129. Section {
  130. Button {
  131. keepForNextWiew = true
  132. state.add()
  133. }
  134. label: { Text(exceededMaxBolus ? "Max Bolus exceeded!" : "Enact bolus") }
  135. .frame(maxWidth: .infinity, alignment: .center)
  136. .disabled(disabled)
  137. .listRowBackground(!disabled ? Color(.systemBlue) : Color(.systemGray4))
  138. .tint(.white)
  139. }
  140. }
  141. if state.amount <= 0 {
  142. Section {
  143. Button {
  144. keepForNextWiew = true
  145. state.showModal(for: nil)
  146. }
  147. label: { Text("Continue without bolus") }.frame(maxWidth: .infinity, alignment: .center)
  148. }
  149. }
  150. }
  151. .blur(radius: showInfo ? 3 : 0)
  152. .navigationTitle("Enact Bolus")
  153. .navigationBarTitleDisplayMode(.inline)
  154. .navigationBarItems(
  155. leading: Button {
  156. carbsView()
  157. }
  158. label: {
  159. HStack {
  160. Image(systemName: "chevron.backward")
  161. Text("Meal")
  162. }
  163. },
  164. trailing: Button { state.hideModal() }
  165. label: { Text("Close") }
  166. )
  167. .onAppear {
  168. configureView {
  169. state.waitForSuggestionInitial = waitForSuggestion
  170. state.waitForSuggestion = waitForSuggestion
  171. state.insulinCalculated = state.calculateInsulin()
  172. }
  173. }
  174. .onDisappear {
  175. if fetch, hasFatOrProtein, !keepForNextWiew, state.useCalc {
  176. state.delete(deleteTwice: true, meal: meal)
  177. } else if fetch, !keepForNextWiew, state.useCalc {
  178. state.delete(deleteTwice: false, meal: meal)
  179. }
  180. }
  181. .popup(isPresented: showInfo) {
  182. bolusInfoAlternativeCalculator
  183. }
  184. }
  185. var predictionChart: some View {
  186. ZStack {
  187. PredictionView(
  188. predictions: $state.predictions, units: $state.units, eventualBG: $state.evBG, target: $state.target,
  189. displayPredictions: $state.displayPredictions
  190. )
  191. }
  192. }
  193. // Pop-up
  194. var bolusInfoAlternativeCalculator: some View {
  195. VStack {
  196. VStack {
  197. VStack(spacing: Config.spacing) {
  198. HStack {
  199. Text("Calculations")
  200. .font(.title3).frame(maxWidth: .infinity, alignment: .center)
  201. }.padding(10)
  202. if fetch {
  203. mealEntries.padding()
  204. Divider().frame(height: Config.dividerHeight) // .overlay(Config.overlayColour)
  205. }
  206. settings.padding()
  207. }
  208. Divider().frame(height: Config.dividerHeight) // .overlay(Config.overlayColour)
  209. insulinParts.padding()
  210. Divider().frame(height: Config.dividerHeight) // .overlay(Config.overlayColour)
  211. VStack {
  212. HStack {
  213. Text("Full Bolus")
  214. .foregroundColor(.secondary)
  215. Spacer()
  216. let insulin = state.roundedWholeCalc
  217. Text(insulin.formatted()).foregroundStyle(state.roundedWholeCalc < 0 ? Color.loopRed : Color.primary)
  218. Text(" U")
  219. .foregroundColor(.secondary)
  220. }
  221. }.padding(.horizontal)
  222. Divider().frame(height: Config.dividerHeight)
  223. results.padding()
  224. Divider().frame(height: Config.dividerHeight) // .overlay(Config.overlayColour)
  225. if exceededMaxBolus {
  226. HStack {
  227. let maxBolus = state.maxBolus
  228. let maxBolusFormatted = maxBolus.formatted()
  229. Text("Your entered amount was limited by your max Bolus setting of \(maxBolusFormatted)\(" U")")
  230. }
  231. .padding()
  232. .fontWeight(.semibold)
  233. .foregroundStyle(Color.loopRed)
  234. }
  235. }
  236. .padding(.top, 10)
  237. .padding(.bottom, 15)
  238. // Hide pop-up
  239. VStack {
  240. Button { showInfo = false }
  241. label: { Text("OK") }
  242. .frame(maxWidth: .infinity, alignment: .center)
  243. .font(.system(size: 16))
  244. .fontWeight(.semibold)
  245. .foregroundColor(.blue)
  246. }
  247. .padding(.bottom, 20)
  248. }
  249. .font(.footnote)
  250. .background(
  251. RoundedRectangle(cornerRadius: 10, style: .continuous)
  252. .fill(Color(colorScheme == .dark ? UIColor.systemGray4 : UIColor.systemGray4).opacity(0.9))
  253. )
  254. }
  255. private var disabled: Bool {
  256. state.amount <= 0 || state.amount > state.maxBolus
  257. }
  258. var changed: Bool {
  259. ((meal.first?.carbs ?? 0) > 0) || ((meal.first?.fat ?? 0) > 0) || ((meal.first?.protein ?? 0) > 0)
  260. }
  261. var hasFatOrProtein: Bool {
  262. ((meal.first?.fat ?? 0) > 0) || ((meal.first?.protein ?? 0) > 0)
  263. }
  264. func carbsView() {
  265. if fetch {
  266. keepForNextWiew = true
  267. state.backToCarbsView(complexEntry: true, meal, override: false)
  268. } else {
  269. state.backToCarbsView(complexEntry: false, meal, override: true)
  270. }
  271. }
  272. var mealEntries: some View {
  273. VStack {
  274. if let carbs = meal.first?.carbs, carbs > 0 {
  275. HStack {
  276. Text("Carbs")
  277. Spacer()
  278. Text(carbs.formatted())
  279. Text("g")
  280. }.foregroundColor(.secondary)
  281. }
  282. if let fat = meal.first?.fat, fat > 0 {
  283. HStack {
  284. Text("Fat")
  285. Spacer()
  286. Text(fat.formatted())
  287. Text("g")
  288. }.foregroundColor(.secondary)
  289. }
  290. if let protein = meal.first?.protein, protein > 0 {
  291. HStack {
  292. Text("Protein")
  293. Spacer()
  294. Text(protein.formatted())
  295. Text("g")
  296. }.foregroundColor(.secondary)
  297. }
  298. if let note = meal.first?.note, note != "" {
  299. HStack {
  300. Text("Note")
  301. Spacer()
  302. Text(note)
  303. }.foregroundColor(.secondary)
  304. }
  305. }
  306. }
  307. var settings: some View {
  308. VStack {
  309. HStack {
  310. Text("Carb Ratio")
  311. .foregroundColor(.secondary)
  312. Spacer()
  313. Text(state.carbRatio.formatted())
  314. Text(NSLocalizedString(" g/U", comment: " grams per Unit"))
  315. .foregroundColor(.secondary)
  316. }
  317. HStack {
  318. Text("ISF")
  319. .foregroundColor(.secondary)
  320. Spacer()
  321. let isf = state.isf
  322. Text(isf.formatted())
  323. Text(state.units.rawValue + NSLocalizedString("/U", comment: "/Insulin unit"))
  324. .foregroundColor(.secondary)
  325. }
  326. HStack {
  327. Text("Target Glucose")
  328. .foregroundColor(.secondary)
  329. Spacer()
  330. let target = state.units == .mmolL ? state.target.asMmolL : state.target
  331. Text(
  332. target
  333. .formatted(.number.grouping(.never).rounded().precision(.fractionLength(fractionDigits)))
  334. )
  335. Text(state.units.rawValue)
  336. .foregroundColor(.secondary)
  337. }
  338. HStack {
  339. Text("Basal")
  340. .foregroundColor(.secondary)
  341. Spacer()
  342. let basal = state.basal
  343. Text(basal.formatted())
  344. Text(NSLocalizedString(" U/h", comment: " Units per hour"))
  345. .foregroundColor(.secondary)
  346. }
  347. HStack {
  348. Text("Fraction")
  349. .foregroundColor(.secondary)
  350. Spacer()
  351. let fraction = state.fraction
  352. Text(fraction.formatted())
  353. }
  354. if state.useFattyMealCorrectionFactor {
  355. HStack {
  356. Text("Fatty Meal Factor")
  357. .foregroundColor(.orange)
  358. Spacer()
  359. let fraction = state.fattyMealFactor
  360. Text(fraction.formatted())
  361. .foregroundColor(.orange)
  362. }
  363. }
  364. }
  365. }
  366. var insulinParts: some View {
  367. VStack(spacing: Config.spacing) {
  368. HStack {
  369. Text("Glucose")
  370. .foregroundColor(.secondary)
  371. Spacer()
  372. let glucose = state.units == .mmolL ? state.currentBG.asMmolL : state.currentBG
  373. Text(glucose.formatted(.number.grouping(.never).rounded().precision(.fractionLength(fractionDigits))))
  374. Text(state.units.rawValue)
  375. .foregroundColor(.secondary)
  376. Spacer()
  377. Image(systemName: "arrow.right")
  378. Spacer()
  379. let targetDifferenceInsulin = state.targetDifferenceInsulin
  380. // rounding
  381. let targetDifferenceInsulinAsDouble = NSDecimalNumber(decimal: targetDifferenceInsulin).doubleValue
  382. let roundedTargetDifferenceInsulin = Decimal(round(100 * targetDifferenceInsulinAsDouble) / 100)
  383. Text(roundedTargetDifferenceInsulin.formatted())
  384. Text(" U")
  385. .foregroundColor(.secondary)
  386. }
  387. HStack {
  388. Text("IOB")
  389. .foregroundColor(.secondary)
  390. Spacer()
  391. let iob = state.iob
  392. // rounding
  393. let iobAsDouble = NSDecimalNumber(decimal: iob).doubleValue
  394. let roundedIob = Decimal(round(100 * iobAsDouble) / 100)
  395. Text(roundedIob.formatted())
  396. Text(" U")
  397. .foregroundColor(.secondary)
  398. Spacer()
  399. Image(systemName: "arrow.right")
  400. Spacer()
  401. let iobCalc = state.iobInsulinReduction
  402. // rounding
  403. let iobCalcAsDouble = NSDecimalNumber(decimal: iobCalc).doubleValue
  404. let roundedIobCalc = Decimal(round(100 * iobCalcAsDouble) / 100)
  405. Text(roundedIobCalc.formatted())
  406. Text(" U").foregroundColor(.secondary)
  407. }
  408. HStack {
  409. Text("Trend")
  410. .foregroundColor(.secondary)
  411. Spacer()
  412. let trend = state.units == .mmolL ? state.deltaBG.asMmolL : state.deltaBG
  413. Text(trend.formatted(.number.grouping(.never).rounded().precision(.fractionLength(fractionDigits))))
  414. Text(state.units.rawValue).foregroundColor(.secondary)
  415. Spacer()
  416. Image(systemName: "arrow.right")
  417. Spacer()
  418. let trendInsulin = state.fifteenMinInsulin
  419. // rounding
  420. let trendInsulinAsDouble = NSDecimalNumber(decimal: trendInsulin).doubleValue
  421. let roundedTrendInsulin = Decimal(round(100 * trendInsulinAsDouble) / 100)
  422. Text(roundedTrendInsulin.formatted())
  423. Text(" U")
  424. .foregroundColor(.secondary)
  425. }
  426. HStack {
  427. Text("COB")
  428. .foregroundColor(.secondary)
  429. Spacer()
  430. let cob = state.cob
  431. Text(cob.formatted())
  432. let unitGrams = NSLocalizedString(" g", comment: "grams")
  433. Text(unitGrams).foregroundColor(.secondary)
  434. Spacer()
  435. Image(systemName: "arrow.right")
  436. Spacer()
  437. let insulinCob = state.wholeCobInsulin
  438. // rounding
  439. let insulinCobAsDouble = NSDecimalNumber(decimal: insulinCob).doubleValue
  440. let roundedInsulinCob = Decimal(round(100 * insulinCobAsDouble) / 100)
  441. Text(roundedInsulinCob.formatted())
  442. Text(" U")
  443. .foregroundColor(.secondary)
  444. }
  445. }
  446. }
  447. var results: some View {
  448. VStack {
  449. HStack {
  450. Text("Result")
  451. .fontWeight(.bold)
  452. Spacer()
  453. let fraction = state.fraction
  454. Text(fraction.formatted())
  455. Text(" x ")
  456. .foregroundColor(.secondary)
  457. // if fatty meal is chosen
  458. if state.useFattyMealCorrectionFactor {
  459. let fattyMealFactor = state.fattyMealFactor
  460. Text(fattyMealFactor.formatted())
  461. .foregroundColor(.orange)
  462. Text(" x ")
  463. .foregroundColor(.secondary)
  464. }
  465. let insulin = state.roundedWholeCalc
  466. Text(insulin.formatted()).foregroundStyle(state.roundedWholeCalc < 0 ? Color.loopRed : Color.primary)
  467. Text(" U")
  468. .foregroundColor(.secondary)
  469. Text(" = ")
  470. .foregroundColor(.secondary)
  471. let result = state.insulinCalculated
  472. // rounding
  473. let resultAsDouble = NSDecimalNumber(decimal: result).doubleValue
  474. let roundedResult = Decimal(round(100 * resultAsDouble) / 100)
  475. Text(roundedResult.formatted())
  476. .fontWeight(.bold)
  477. .font(.system(size: 16))
  478. .foregroundColor(.blue)
  479. Text(" U")
  480. .foregroundColor(.secondary)
  481. }
  482. }
  483. }
  484. }
  485. }