AlternativeBolusCalcRootView.swift 20 KB

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