AlternativeBolusCalcRootView.swift 21 KB

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