AlternativeBolusCalcRootView.swift 21 KB

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