-
Notifications
You must be signed in to change notification settings - Fork 1
/
My AlternativeBolusCalcRootView.swift
556 lines (516 loc) · 22.7 KB
/
My AlternativeBolusCalcRootView.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
import Charts
import CoreData
import SwiftUI
import Swinject
extension Bolus {
struct AlternativeBolusCalcRootView: BaseView {
let resolver: Resolver
let waitForSuggestion: Bool
let fetch: Bool
@StateObject var state: StateModel
@State private var showInfo = false
@State private var exceededMaxBolus = false
@State private var keepForNextWiew: Bool = false
private enum Config {
static let dividerHeight: CGFloat = 2
static let overlayColour: Color = .white // Currently commented out
static let spacing: CGFloat = 3
}
@Environment(\.colorScheme) var colorScheme
@FocusState private var isFocused: Bool
@FetchRequest(
entity: Meals.entity(),
sortDescriptors: [NSSortDescriptor(key: "createdAt", ascending: false)]
) var meal: FetchedResults<Meals>
private var formatter: NumberFormatter {
let formatter = NumberFormatter()
formatter.numberStyle = .decimal
formatter.maximumFractionDigits = 2
return formatter
}
private var mealFormatter: NumberFormatter {
let formatter = NumberFormatter()
formatter.numberStyle = .decimal
formatter.maximumFractionDigits = 1
return formatter
}
private var gluoseFormatter: NumberFormatter {
let formatter = NumberFormatter()
formatter.numberStyle = .decimal
if state.units == .mmolL {
formatter.maximumFractionDigits = 1
} else { formatter.maximumFractionDigits = 0 }
return formatter
}
private var fractionDigits: Int {
if state.units == .mmolL {
return 1
} else { return 0 }
}
var body: some View {
Form {
Section {
if state.waitForSuggestion {
Text("Please wait")
} else {
predictionChart
}
} header: { Text("Predictions") }
Section {}
if fetch {
Section {
mealEntries
} header: { Text("Meal Summary") }
}
Section {
HStack {
Button(action: {
showInfo.toggle()
}, label: {
Image(systemName: "info.circle")
Text("Calculations")
})
.foregroundStyle(.blue)
.font(.footnote)
.buttonStyle(PlainButtonStyle())
.frame(maxWidth: .infinity, alignment: .leading)
// Highjackig Fatty Meals Functionality to enable calculation of insulin using latest carbs or COB
if state.fattyMeals {
Spacer()
Toggle(isOn: $state.useFattyMealCorrectionFactor) {
Text("Calculate Insulin")
}
.toggleStyle(CheckboxToggleStyle())
.font(.footnote)
.onChange(of: state.useFattyMealCorrectionFactor) { _ in
if let carbs2 = meal.first?.carbs, carbs2 > 0 {
state.insulinCalculated = state.calculateInsulin(carbs2: Decimal(carbs2))
} else {
let carbs2 = 0
state.insulinCalculated = state.calculateInsulin(carbs2: Decimal(carbs2))
}
}
}
}
if state.waitForSuggestion {
HStack {
Text("Wait please").foregroundColor(.secondary)
Spacer()
ActivityIndicator(isAnimating: .constant(true), style: .medium) // fix iOS 15 bug
}
} else {
HStack {
Text("Recommended Bolus")
Spacer()
Text(
formatter
.string(from: Double(state.insulinCalculated) as NSNumber) ?? ""
)
Text(
NSLocalizedString(" U", comment: "Unit in number of units delivered (keep the space character!)")
).foregroundColor(.secondary)
}.contentShape(Rectangle())
.onTapGesture { state.amount = state.insulinCalculated }
}
HStack {
Text("Bolus")
Spacer()
DecimalTextField(
"0",
value: $state.amount,
formatter: formatter,
cleanInput: true,
useButtons: false
)
Text(exceededMaxBolus ? "😵" : " U").foregroundColor(.secondary)
}
.focused($isFocused)
.onChange(of: state.amount) { newValue in
if newValue > state.maxBolus {
exceededMaxBolus = true
} else {
exceededMaxBolus = false
}
}
} header: {
HStack {
Text("Bolus")
if isFocused {
Button { isFocused = false } label: {
HStack {
Text("Hide").foregroundStyle(.gray)
Image(systemName: "keyboard")
.symbolRenderingMode(.monochrome).foregroundStyle(colorScheme == .dark ? .white : .black)
}.frame(maxWidth: .infinity, alignment: .trailing)
}
.controlSize(.mini)
}
}
}
if state.amount > 0 {
Section {
Button {
keepForNextWiew = true
state.add()
}
label: { Text(exceededMaxBolus ? "Max Bolus exceeded!" : "Enact bolus") }
.frame(maxWidth: .infinity, alignment: .center)
.disabled(disabled)
.listRowBackground(!disabled ? Color(.systemBlue) : Color(.systemGray4))
.tint(.white)
}
}
if state.amount <= 0 {
Section {
Button {
keepForNextWiew = true
state.showModal(for: nil)
}
label: { Text("Continue without bolus") }.frame(maxWidth: .infinity, alignment: .center)
}
}
}
.dynamicTypeSize(...DynamicTypeSize.xxLarge)
.blur(radius: showInfo ? 20 : 0)
.navigationTitle("Enact Bolus")
.navigationBarTitleDisplayMode(.inline)
.navigationBarItems(
leading: Button {
carbsView()
}
label: {
HStack {
Image(systemName: "chevron.backward")
Text("Meal")
}
},
trailing: Button { state.hideModal() }
label: { Text("Close") }
)
.onAppear {
configureView {
state.waitForSuggestionInitial = waitForSuggestion
state.waitForSuggestion = waitForSuggestion
if let carbs2 = meal.first?.carbs, carbs2 > 0 {
state.insulinCalculated = state.calculateInsulin(carbs2: Decimal(carbs2))
} else {
// Provide a default value for carbs if necessary
let carbs2 = 0
state.insulinCalculated = state.calculateInsulin(carbs2: Decimal(carbs2))
}
}
}
.onDisappear {
if fetch, hasFatOrProtein, !keepForNextWiew, state.useCalc {
state.delete(deleteTwice: true, meal: meal)
} else if fetch, !keepForNextWiew, state.useCalc {
state.delete(deleteTwice: false, meal: meal)
}
}
.popup(isPresented: showInfo) {
bolusInfoAlternativeCalculator
}
}
var predictionChart: some View {
ZStack {
PredictionView(
predictions: $state.predictions, units: $state.units, eventualBG: $state.evBG, target: $state.target,
displayPredictions: $state.displayPredictions
)
}
}
// Pop-up
var bolusInfoAlternativeCalculator: some View {
VStack {
VStack {
VStack(spacing: Config.spacing) {
HStack {
Text("Calculations")
.font(.title3).frame(maxWidth: .infinity, alignment: .center)
}.padding(10)
if fetch {
mealEntries.padding()
Divider().frame(height: Config.dividerHeight) // .overlay(Config.overlayColour)
}
settings.padding()
}
Divider().frame(height: Config.dividerHeight) // .overlay(Config.overlayColour)
insulinParts.padding()
Divider().frame(height: Config.dividerHeight) // .overlay(Config.overlayColour)
VStack {
HStack {
let logMessage = state.logMessage
// Combine "Full Bolus", log message, and potential styling
Text("Full Bolus " + (logMessage.isEmpty ? "" : "(\(logMessage))"))
.foregroundColor(logMessage.isEmpty ? .secondary : .yellow) // Optional highlight
Spacer()
let insulin = state.roundedWholeCalc
Text(insulin.formatted()).foregroundStyle(state.roundedWholeCalc < 0 ? Color.loopRed : Color.primary)
Text(" U")
.foregroundColor(.secondary)
}
}.padding(.horizontal)
Divider().frame(height: Config.dividerHeight)
results.padding()
Divider().frame(height: Config.dividerHeight) // .overlay(Config.overlayColour)
if exceededMaxBolus {
HStack {
let maxBolus = state.maxBolus
let maxBolusFormatted = maxBolus.formatted()
Text("Your entered amount was limited by your max Bolus setting of \(maxBolusFormatted)\(" U")")
}
.padding()
.fontWeight(.semibold)
.foregroundStyle(Color.loopRed)
}
}
.padding(.top, 10)
.padding(.bottom, 15)
// Hide pop-up
VStack {
Button { showInfo = false }
label: { Text("OK") }
.frame(maxWidth: .infinity, alignment: .center)
.font(.system(size: 16))
.fontWeight(.semibold)
.foregroundColor(.blue)
}
.padding(.bottom, 20)
}
.font(.footnote)
.background(
RoundedRectangle(cornerRadius: 10, style: .continuous)
.fill(Color(colorScheme == .dark ? UIColor.systemGray4 : UIColor.systemGray4).opacity(0.9))
)
}
private var disabled: Bool {
state.amount <= 0 || state.amount > state.maxBolus
}
var changed: Bool {
((meal.first?.carbs ?? 0) > 0) || ((meal.first?.fat ?? 0) > 0) || ((meal.first?.protein ?? 0) > 0)
}
var hasFatOrProtein: Bool {
((meal.first?.fat ?? 0) > 0) || ((meal.first?.protein ?? 0) > 0)
}
func carbsView() {
if fetch {
keepForNextWiew = true
state.backToCarbsView(complexEntry: true, meal, override: false)
} else {
state.backToCarbsView(complexEntry: false, meal, override: true)
}
}
var mealEntries: some View {
VStack {
if let carbs = meal.first?.carbs, carbs > 0 {
HStack {
Text("Carbs")
Spacer()
Text(carbs.formatted())
Text("g")
}.foregroundColor(.secondary)
}
if let fat = meal.first?.fat, fat > 0 {
HStack {
Text("Fat")
Spacer()
Text(fat.formatted())
Text("g")
}.foregroundColor(.secondary)
}
if let protein = meal.first?.protein, protein > 0 {
HStack {
Text("Protein")
Spacer()
Text(protein.formatted())
Text("g")
}.foregroundColor(.secondary)
}
if let note = meal.first?.note, note != "" {
HStack {
Text("Note")
Spacer()
Text(note)
}.foregroundColor(.secondary)
}
}
}
var settings: some View {
VStack {
HStack {
Text("Carb Ratio")
.foregroundColor(.secondary)
Spacer()
Text(state.carbRatio.formatted())
Text(NSLocalizedString(" g/U", comment: " grams per Unit"))
.foregroundColor(.secondary)
}
HStack {
Text("ISF")
.foregroundColor(.secondary)
Spacer()
let isf = state.isf
Text(isf.formatted())
Text(state.units.rawValue + NSLocalizedString("/U", comment: "/Insulin unit"))
.foregroundColor(.secondary)
}
HStack {
Text("Target Glucose")
.foregroundColor(.secondary)
Spacer()
let target = state.units == .mmolL ? state.target.asMmolL : state.target
Text(
target
.formatted(.number.grouping(.never).rounded().precision(.fractionLength(fractionDigits)))
)
Text(state.units.rawValue)
.foregroundColor(.secondary)
}
HStack {
Text("Basal")
.foregroundColor(.secondary)
Spacer()
let basal = state.basal
Text(basal.formatted())
Text(NSLocalizedString(" U/h", comment: " Units per hour"))
.foregroundColor(.secondary)
}
HStack {
Text("COB Fraction")
.foregroundColor(.secondary)
Spacer()
let fraction = state.fraction
Text(fraction.formatted())
}
if state.useFattyMealCorrectionFactor {
HStack {
Text("Carb Entry Fraction")
.foregroundColor(.orange)
Spacer()
let fraction = state.fattyMealFactor
Text(fraction.formatted())
.foregroundColor(.orange)
}
}
}
}
var insulinParts: some View {
VStack(spacing: Config.spacing) {
HStack {
Text("Glucose")
.foregroundColor(.secondary)
Spacer()
let glucose = state.units == .mmolL ? state.currentBG.asMmolL : state.currentBG
Text(glucose.formatted(.number.grouping(.never).rounded().precision(.fractionLength(fractionDigits))))
Text(state.units.rawValue)
.foregroundColor(.secondary)
Spacer()
Image(systemName: "arrow.right")
Spacer()
let targetDifferenceInsulin = state.targetDifferenceInsulin
// rounding
let targetDifferenceInsulinAsDouble = NSDecimalNumber(decimal: targetDifferenceInsulin).doubleValue
let roundedTargetDifferenceInsulin = Decimal(round(100 * targetDifferenceInsulinAsDouble) / 100)
Text(roundedTargetDifferenceInsulin.formatted())
Text(" U")
.foregroundColor(.secondary)
}
HStack {
Text("IOB")
.foregroundColor(.secondary)
Spacer()
let iob = state.iob
// rounding
let iobAsDouble = NSDecimalNumber(decimal: iob).doubleValue
let roundedIob = Decimal(round(100 * iobAsDouble) / 100)
Text(roundedIob.formatted())
Text(" U")
.foregroundColor(.secondary)
Spacer()
Image(systemName: "arrow.right")
Spacer()
let iobCalc = state.iobInsulinReduction
// rounding
let iobCalcAsDouble = NSDecimalNumber(decimal: iobCalc).doubleValue
let roundedIobCalc = Decimal(round(100 * iobCalcAsDouble) / 100)
Text(roundedIobCalc.formatted())
Text(" U").foregroundColor(.secondary)
}
HStack {
Text("Trend")
.foregroundColor(.secondary)
Spacer()
let trend = state.units == .mmolL ? state.deltaBG.asMmolL : state.deltaBG
Text(trend.formatted(.number.grouping(.never).rounded().precision(.fractionLength(fractionDigits))))
Text(state.units.rawValue).foregroundColor(.secondary)
Spacer()
Image(systemName: "arrow.right")
Spacer()
let trendInsulin = state.fifteenMinInsulin
// rounding
let trendInsulinAsDouble = NSDecimalNumber(decimal: trendInsulin).doubleValue
let roundedTrendInsulin = Decimal(round(100 * trendInsulinAsDouble) / 100)
Text(roundedTrendInsulin.formatted())
Text(" U")
.foregroundColor(.secondary)
}
HStack {
Text("COB")
.foregroundColor(.secondary)
Spacer()
let cob = state.cob
Text(cob.formatted())
let unitGrams = NSLocalizedString(" g", comment: "grams")
Text(unitGrams).foregroundColor(.secondary)
Spacer()
Image(systemName: "arrow.right")
Spacer()
let insulinCob = state.wholeCobInsulin
// rounding
let insulinCobAsDouble = NSDecimalNumber(decimal: insulinCob).doubleValue
let roundedInsulinCob = Decimal(round(100 * insulinCobAsDouble) / 100)
Text(roundedInsulinCob.formatted())
Text(" U")
.foregroundColor(.secondary)
}
}
}
var results: some View {
VStack {
HStack {
Text("Result")
.fontWeight(.bold)
Spacer()
let fraction = state.fraction
Text(fraction.formatted())
Text(" x ")
.foregroundColor(.secondary)
// if fatty meal is chosen
if state.useFattyMealCorrectionFactor {
let fattyMealFactor = state.fattyMealFactor
Text(fattyMealFactor.formatted())
.foregroundColor(.orange)
Text(" x ")
.foregroundColor(.secondary)
}
let insulin = state.roundedWholeCalc
Text(insulin.formatted()).foregroundStyle(state.roundedWholeCalc < 0 ? Color.loopRed : Color.primary)
Text(" U")
.foregroundColor(.secondary)
Text(" = ")
.foregroundColor(.secondary)
let result = state.insulinCalculated
// rounding
let resultAsDouble = NSDecimalNumber(decimal: result).doubleValue
let roundedResult = Decimal(round(100 * resultAsDouble) / 100)
Text(roundedResult.formatted())
.fontWeight(.bold)
.font(.system(size: 16))
.foregroundColor(.blue)
Text(" U")
.foregroundColor(.secondary)
}
}
}
}
}