AlternativeBolusCalcRootView.swift 21 KB

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