AlternativeBolusCalcRootView.swift 24 KB

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