AddTempTargetForm.swift 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400
  1. import Foundation
  2. import SwiftUI
  3. struct AddTempTargetForm: View {
  4. @StateObject var state: Adjustments.StateModel
  5. @Environment(\.presentationMode) var presentationMode
  6. @Environment(\.colorScheme) var colorScheme
  7. @Environment(AppState.self) var appState
  8. @Environment(\.dismiss) var dismiss
  9. @State private var displayPickerDuration: Bool = false
  10. @State private var displayPickerTarget: Bool = false
  11. @State private var tempTargetSensitivityAdjustmentType: TempTargetSensitivityAdjustmentType = .standard
  12. @State private var durationHours = 0
  13. @State private var durationMinutes = 0
  14. @State private var targetStep: Decimal = 5
  15. @State private var showAlert = false
  16. @State private var showPresetAlert = false
  17. @State private var alertString = ""
  18. @State private var isUsingSlider = false
  19. @State private var hasChanges = false
  20. @State private var didPressSave =
  21. false // only used for fixing the Disclaimer showing up after pressing save (after the state was resetted), maybe refactor this...
  22. @State private var shouldDisplayHint = false
  23. @State var hintDetent = PresentationDetent.large
  24. @State var selectedVerboseHint: String?
  25. @State var hintLabel: String?
  26. var isCustomizedAdjustSens: Bool = false
  27. var body: some View {
  28. NavigationView {
  29. List {
  30. addTempTarget()
  31. saveButton
  32. }
  33. .listSectionSpacing(10)
  34. .padding(.top, 30)
  35. .ignoresSafeArea(edges: .top)
  36. .scrollContentBackground(.hidden)
  37. .background(appState.trioBackgroundColor(for: colorScheme))
  38. .navigationTitle("Add Temp Target")
  39. .navigationBarTitleDisplayMode(.inline)
  40. .toolbar {
  41. ToolbarItem(placement: .topBarLeading) {
  42. Button(action: {
  43. presentationMode.wrappedValue.dismiss()
  44. }, label: {
  45. Text("Cancel")
  46. })
  47. }
  48. ToolbarItem(placement: .topBarTrailing) {
  49. Button(
  50. action: {
  51. state.isHelpSheetPresented.toggle()
  52. },
  53. label: {
  54. Image(systemName: "questionmark.circle")
  55. }
  56. )
  57. }
  58. }
  59. .onAppear {
  60. targetStep = state.units == .mgdL ? 5 : 9
  61. state.tempTargetTarget = state.normalTarget
  62. }
  63. .sheet(isPresented: $state.isHelpSheetPresented) {
  64. NavigationStack {
  65. List {
  66. VStack(alignment: .leading, spacing: 10) {
  67. Text(
  68. "A Temporary Target replaces the current Target Glucose specified in Therapy settings."
  69. )
  70. Text(
  71. "Depending on the Algorithm > Target Behavior settings, these temporary glucose targets can also raise Insulin Sensitivity for high targets or lower sensitivity for low targets."
  72. )
  73. Text(
  74. "Furthermore, you could adjust that sensitivity change independently from the Half Basal Exercise Target specified in Algorithm > Target Behavior settings by deliberatly setting a customized Insulin Percentage for a Temp Target."
  75. )
  76. Text(
  77. "A pre-condition to have Temp Targets adjust Sensitivity is that the respective Target Behavior settings High Temp Target Raises Sensitivity or Low Temp Target Lowers Sensitivity are set to enabled!"
  78. )
  79. }
  80. }
  81. .padding(.trailing, 10)
  82. .navigationBarTitle("Help", displayMode: .inline)
  83. Button { state.isHelpSheetPresented.toggle() }
  84. label: { Text("Got it!").frame(maxWidth: .infinity, alignment: .center) }
  85. .buttonStyle(.bordered)
  86. .padding(.top)
  87. }
  88. .padding()
  89. .presentationDetents(
  90. [.fraction(0.9), .large],
  91. selection: $state.helpSheetDetent
  92. )
  93. }
  94. }
  95. }
  96. @ViewBuilder private func addTempTarget() -> some View {
  97. Group {
  98. Section {
  99. HStack {
  100. Text("Name")
  101. Spacer()
  102. TextField("(Optional)", text: $state.tempTargetName)
  103. .multilineTextAlignment(.trailing)
  104. }
  105. }.listRowBackground(Color.chart)
  106. Section {
  107. let settingsProvider = PickerSettingsProvider.shared
  108. let glucoseSetting = PickerSetting(value: 0, step: targetStep, min: 80, max: 200, type: .glucose)
  109. TargetPicker(
  110. label: "Target Glucose",
  111. selection: Binding(
  112. get: { state.tempTargetTarget },
  113. set: { state.tempTargetTarget = $0 }
  114. ),
  115. options: settingsProvider.generatePickerValues(
  116. from: glucoseSetting,
  117. units: state.units,
  118. roundMinToStep: true
  119. ),
  120. units: state.units,
  121. hasChanges: $hasChanges,
  122. targetStep: $targetStep,
  123. displayPickerTarget: $displayPickerTarget,
  124. toggleScrollWheel: toggleScrollWheel
  125. )
  126. .onChange(of: state.tempTargetTarget) {
  127. state.percentage = state.computeAdjustedPercentage()
  128. }
  129. }
  130. .listRowBackground(Color.chart)
  131. if state.tempTargetTarget != state.normalTarget {
  132. let computedHalfBasalTarget = Decimal(state.computeHalfBasalTarget())
  133. if state.isAdjustSensEnabled() {
  134. Section(
  135. footer: state.percentageDescription(state.percentage),
  136. content: {
  137. Picker("Sensitivity Adjustment", selection: $tempTargetSensitivityAdjustmentType) {
  138. ForEach(TempTargetSensitivityAdjustmentType.allCases, id: \.self) { option in
  139. Text(option.rawValue).tag(option)
  140. }
  141. .pickerStyle(MenuPickerStyle())
  142. .onChange(of: tempTargetSensitivityAdjustmentType) { _, newValue in
  143. if newValue == .standard {
  144. state.halfBasalTarget = state.settingHalfBasalTarget
  145. state.percentage = state.computeAdjustedPercentage()
  146. }
  147. }
  148. }
  149. Text("\(formattedPercentage(state.percentage))% Insulin")
  150. .foregroundColor(isUsingSlider ? .orange : Color.tabBar)
  151. .font(.title3)
  152. .fontWeight(.bold)
  153. .frame(maxWidth: .infinity, alignment: .center)
  154. if tempTargetSensitivityAdjustmentType == .slider {
  155. Slider(
  156. value: $state.percentage,
  157. in: state.computeSliderLow() ... state.computeSliderHigh(),
  158. step: 5
  159. ) {} minimumValueLabel: {
  160. Text("\(state.computeSliderLow(), specifier: "%.0f")%")
  161. } maximumValueLabel: {
  162. Text("\(state.computeSliderHigh(), specifier: "%.0f")%")
  163. } onEditingChanged: { editing in
  164. isUsingSlider = editing
  165. state.halfBasalTarget = Decimal(state.computeHalfBasalTarget())
  166. }
  167. .listRowSeparator(.hidden, edges: .top)
  168. }
  169. }
  170. )
  171. .listRowBackground(Color.chart)
  172. }
  173. }
  174. Section {
  175. DatePicker("Start Time", selection: $state.date, in: Date.now...)
  176. }.listRowBackground(Color.chart)
  177. Section {
  178. VStack {
  179. HStack {
  180. Text("Duration")
  181. Spacer()
  182. Text(state.formatHrMin(Int(state.tempTargetDuration)))
  183. .foregroundColor(
  184. !displayPickerDuration ?
  185. (state.tempTargetDuration > 0 ? .primary : .secondary) : .accentColor
  186. )
  187. .onTapGesture {
  188. displayPickerDuration = toggleScrollWheel(displayPickerDuration)
  189. }
  190. }
  191. if displayPickerDuration {
  192. HStack {
  193. Picker("Hours", selection: $durationHours) {
  194. ForEach(0 ..< 24) { hour in
  195. Text("\(hour) hr").tag(hour)
  196. }
  197. }
  198. .pickerStyle(WheelPickerStyle())
  199. .frame(maxWidth: .infinity)
  200. .onChange(of: durationHours) {
  201. state.tempTargetDuration = Decimal(totalDurationInMinutes())
  202. }
  203. Picker("Minutes", selection: $durationMinutes) {
  204. ForEach(Array(stride(from: 0, through: 55, by: 5)), id: \.self) { minute in
  205. Text("\(minute) min").tag(minute)
  206. }
  207. }
  208. .pickerStyle(WheelPickerStyle())
  209. .frame(maxWidth: .infinity)
  210. .onChange(of: durationMinutes) {
  211. state.tempTargetDuration = Decimal(totalDurationInMinutes())
  212. }
  213. }
  214. }
  215. }
  216. }.listRowBackground(Color.chart)
  217. }
  218. }
  219. private func isTempTargetInvalid() -> (Bool, String?) {
  220. let noDurationSpecified = state.tempTargetDuration == 0
  221. let targetZero = state.tempTargetTarget < 80
  222. if noDurationSpecified {
  223. return (true, "Set a duration!")
  224. }
  225. if targetZero {
  226. return (
  227. true,
  228. "\(state.units == .mgdL ? "80 " : "4.4 ")" + state.units.rawValue + " needed as min. Glucose Target!"
  229. )
  230. }
  231. return (false, nil)
  232. }
  233. private func isSavePresetInvalid() -> (Bool, String?) {
  234. let (isTempTargetInvalid, tempTargetError) = isTempTargetInvalid()
  235. let isDateInFuture = state.date > Date()
  236. if isTempTargetInvalid {
  237. return (true, tempTargetError)
  238. }
  239. if isDateInFuture {
  240. return (true, "Presets can't be saved with a future date!")
  241. }
  242. return (false, nil)
  243. }
  244. private var saveButton: some View {
  245. let (isTempTargetInvalid, _) = isTempTargetInvalid()
  246. let (isSavePresetInvalid, savePresetError) = isSavePresetInvalid()
  247. let noNameSpecified = state.tempTargetName == ""
  248. return Group {
  249. Section(
  250. header:
  251. HStack {
  252. Spacer()
  253. Text(savePresetError ?? "").textCase(nil)
  254. .foregroundColor(colorScheme == .dark ? .orange : .accentColor)
  255. Spacer()
  256. },
  257. content: {
  258. Button(action: {
  259. Task {
  260. if noNameSpecified { state.tempTargetName = "Custom Target" }
  261. didPressSave.toggle()
  262. await state.invokeSaveOfCustomTempTargets()
  263. dismiss()
  264. }
  265. }, label: {
  266. Text("Start Temp Target")
  267. })
  268. .disabled(isTempTargetInvalid)
  269. .frame(maxWidth: .infinity, alignment: .center)
  270. .tint(.white)
  271. }
  272. ).listRowBackground(isTempTargetInvalid ? Color(.systemGray4) : Color(.systemBlue))
  273. Section {
  274. Button(action: {
  275. Task {
  276. if noNameSpecified { state.tempTargetName = "Custom Target" }
  277. didPressSave.toggle()
  278. await state.saveTempTargetPreset()
  279. dismiss()
  280. }
  281. }, label: {
  282. Text("Save as Preset")
  283. })
  284. .disabled(isSavePresetInvalid)
  285. .frame(maxWidth: .infinity, alignment: .center)
  286. .tint(.white)
  287. }
  288. .listRowBackground(
  289. isSavePresetInvalid ? Color(.systemGray4) : Color.secondary
  290. )
  291. }
  292. }
  293. private func totalDurationInMinutes() -> Int {
  294. let durationTotal = (durationHours * 60) + durationMinutes
  295. return max(0, durationTotal)
  296. }
  297. private func formattedPercentage(_ value: Double) -> String {
  298. let percentageNumber = NSNumber(value: value)
  299. return Formatter.integerFormatter.string(from: percentageNumber) ?? "\(value)"
  300. }
  301. private func formattedGlucose(glucose: Decimal) -> String {
  302. let formattedValue: String
  303. if state.units == .mgdL {
  304. formattedValue = Formatter.glucoseFormatter(for: state.units).string(from: glucose as NSDecimalNumber) ?? "\(glucose)"
  305. } else {
  306. formattedValue = glucose.formattedAsMmolL
  307. }
  308. return "\(formattedValue) \(state.units.rawValue)"
  309. }
  310. private func roundTargetToStep(_ target: Decimal, _ step: Decimal) -> Decimal {
  311. // Convert target and step to NSDecimalNumber
  312. guard let targetValue = NSDecimalNumber(decimal: target).doubleValue as Double?,
  313. let stepValue = NSDecimalNumber(decimal: step).doubleValue as Double?
  314. else {
  315. print("Failed to unwrap target or step as NSDecimalNumber")
  316. return target
  317. }
  318. // Perform the remainder check using truncatingRemainder
  319. let remainder = Decimal(targetValue.truncatingRemainder(dividingBy: stepValue))
  320. if remainder != 0 {
  321. // Calculate how much to adjust (up or down) based on the remainder
  322. let adjustment = step - remainder
  323. return target + adjustment
  324. }
  325. // Return the original target if no adjustment is needed
  326. return target
  327. }
  328. private func toggleScrollWheel(_ toggle: Bool) -> Bool {
  329. displayPickerDuration = false
  330. displayPickerTarget = false
  331. return !toggle
  332. }
  333. func generateTargetPickerValues() -> [Decimal] {
  334. var values: [Decimal] = []
  335. var currentValue: Double = 80 // lowest allowed TT in oref
  336. let step = Double(targetStep)
  337. // Adjust currentValue to be divisible by targetStep
  338. let remainder = currentValue.truncatingRemainder(dividingBy: step)
  339. if remainder != 0 {
  340. // Move currentValue up to the next value divisible by targetStep
  341. currentValue += (step - remainder)
  342. }
  343. // Now generate the picker values starting from currentValue
  344. while currentValue <= 270 {
  345. values.append(Decimal(currentValue))
  346. currentValue += step
  347. }
  348. // Glucose values are stored as mg/dl values, so Integers.
  349. // Filter out duplicate values when rounded to 1 decimal place.
  350. if state.units == .mmolL {
  351. // Use a Set to track unique values rounded to 1 decimal
  352. var uniqueRoundedValues = Set<String>()
  353. values = values.filter { value in
  354. let roundedValue = String(format: "%.1f", NSDecimalNumber(decimal: value.asMmolL).doubleValue)
  355. return uniqueRoundedValues.insert(roundedValue).inserted
  356. }
  357. }
  358. return values
  359. }
  360. }