AlternativeBolusCalcRootView.swift 21 KB

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