EditTempTargetForm.swift 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404
  1. import Foundation
  2. import SwiftUI
  3. struct EditTempTargetForm: View {
  4. @ObservedObject var tempTarget: TempTargetStored
  5. @Environment(\.presentationMode) var presentationMode
  6. @Environment(\.colorScheme) var colorScheme
  7. @StateObject var state: OverrideConfig.StateModel
  8. @State private var displayPickerDuration: Bool = false
  9. @State private var displayPickerTarget: Bool = false
  10. @State private var tempTargetSensitivityAdjustmentType: TempTargetSensitivityAdjustmentType = .standard
  11. @State private var durationHours = 0
  12. @State private var durationMinutes = 0
  13. @State private var targetStep: Decimal = 1
  14. @State private var name: String
  15. @State private var target: Decimal
  16. @State private var duration: Decimal
  17. @State private var date: Date
  18. @State private var halfBasalTarget: Decimal
  19. @State private var percentage: Decimal
  20. @State private var hasChanges = false
  21. @State private var showAlert = false
  22. @State private var isUsingSlider = false
  23. @State private var isPreset = false
  24. @State private var isEnabled = false
  25. init(tempTargetToEdit: TempTargetStored, state: OverrideConfig.StateModel) {
  26. tempTarget = tempTargetToEdit
  27. _state = StateObject(wrappedValue: state)
  28. _name = State(initialValue: tempTargetToEdit.name ?? "")
  29. _target = State(initialValue: tempTargetToEdit.target?.decimalValue ?? 0)
  30. _duration = State(initialValue: tempTargetToEdit.duration?.decimalValue ?? 0)
  31. _date = State(initialValue: tempTargetToEdit.date ?? Date())
  32. _halfBasalTarget = State(initialValue: tempTargetToEdit.halfBasalTarget?.decimalValue ?? 160)
  33. _isPreset = State(initialValue: tempTargetToEdit.isPreset)
  34. _isEnabled = State(initialValue: tempTargetToEdit.enabled)
  35. if let hbt = tempTargetToEdit.halfBasalTarget?.decimalValue {
  36. let H = hbt
  37. let T = tempTargetToEdit.target?.decimalValue ?? 100
  38. let calcPercentage = Double(state.computeAdjustedPercentage(usingHBT: H, usingTarget: T) * 100)
  39. _percentage = State(initialValue: Decimal(calcPercentage))
  40. } else { _percentage = State(initialValue: Decimal(100)) }
  41. }
  42. var color: LinearGradient {
  43. colorScheme == .dark ? LinearGradient(
  44. gradient: Gradient(colors: [
  45. Color.bgDarkBlue,
  46. Color.bgDarkerDarkBlue
  47. ]),
  48. startPoint: .top,
  49. endPoint: .bottom
  50. ) :
  51. LinearGradient(
  52. gradient: Gradient(colors: [Color.gray.opacity(0.1)]),
  53. startPoint: .top,
  54. endPoint: .bottom
  55. )
  56. }
  57. var body: some View {
  58. NavigationView {
  59. List {
  60. editTempTarget()
  61. saveButton
  62. }
  63. .listSectionSpacing(10)
  64. .listRowSpacing(10)
  65. .padding(.top, 30)
  66. .ignoresSafeArea(edges: .top)
  67. .scrollContentBackground(.hidden).background(color)
  68. .navigationTitle("Edit Temp Target")
  69. .navigationBarTitleDisplayMode(.inline)
  70. .toolbar {
  71. ToolbarItem(placement: .topBarLeading) {
  72. Button(action: {
  73. presentationMode.wrappedValue.dismiss()
  74. }, label: {
  75. Text("Cancel")
  76. })
  77. }
  78. }
  79. .onAppear {
  80. if halfBasalTarget != state.settingHalfBasalTarget { tempTargetSensitivityAdjustmentType = .slider }
  81. }
  82. }
  83. }
  84. @ViewBuilder private func editTempTarget() -> some View {
  85. Group {
  86. Section {
  87. HStack {
  88. Text("Name")
  89. Spacer()
  90. TextField("(Optional)", text: $name)
  91. .multilineTextAlignment(.trailing)
  92. .onChange(of: name) {
  93. hasChanges = true
  94. }
  95. }
  96. }.listRowBackground(Color.chart)
  97. Section {
  98. DatePicker("Date", selection: $date)
  99. .onChange(of: date) { hasChanges = true }
  100. }.listRowBackground(Color.chart)
  101. Section {
  102. VStack {
  103. HStack {
  104. Text("Duration")
  105. Spacer()
  106. Text(formatHrMin(Int(duration)))
  107. .foregroundColor(!displayPickerDuration ? .primary : .accentColor)
  108. }
  109. .onTapGesture {
  110. displayPickerDuration = toggleScrollWheel(displayPickerDuration)
  111. }
  112. .onChange(of: duration) { hasChanges = true }
  113. if displayPickerDuration {
  114. HStack {
  115. Picker(
  116. selection: Binding(
  117. get: {
  118. Int(truncating: duration as NSNumber) / 60
  119. },
  120. set: {
  121. let minutes = Int(truncating: duration as NSNumber) % 60
  122. let totalMinutes = $0 * 60 + minutes
  123. duration = Decimal(totalMinutes)
  124. hasChanges = true
  125. }
  126. ),
  127. label: Text("")
  128. ) {
  129. ForEach(0 ..< 24) { hour in
  130. Text("\(hour) hr").tag(hour)
  131. }
  132. }
  133. .pickerStyle(WheelPickerStyle())
  134. .frame(maxWidth: .infinity)
  135. Picker(
  136. selection: Binding(
  137. get: {
  138. Int(truncating: duration as NSNumber) %
  139. 60 // Convert Decimal to Int for modulus operation
  140. },
  141. set: {
  142. duration = Decimal((Int(truncating: duration as NSNumber) / 60) * 60 + $0)
  143. hasChanges = true
  144. }
  145. ),
  146. label: Text("")
  147. ) {
  148. ForEach(Array(stride(from: 0, through: 55, by: 5)), id: \.self) { minute in
  149. Text("\(minute) min").tag(minute)
  150. }
  151. }
  152. .pickerStyle(WheelPickerStyle())
  153. .frame(maxWidth: .infinity)
  154. }
  155. .listRowSeparator(.hidden, edges: .top)
  156. }
  157. }
  158. }.listRowBackground(Color.chart)
  159. Section {
  160. HStack {
  161. // Picker on the right side
  162. let settingsProvider = PickerSettingsProvider.shared
  163. let glucoseSetting = PickerSetting(value: 0, step: targetStep, min: 80, max: 270, type: .glucose)
  164. TargetPicker(
  165. label: "Target Glucose",
  166. selection: Binding(
  167. get: { target },
  168. set: { target = $0 }
  169. ),
  170. options: settingsProvider.generatePickerValues(
  171. from: glucoseSetting,
  172. units: state.units,
  173. roundMinToStep: true
  174. ),
  175. units: state.units,
  176. hasChanges: $hasChanges,
  177. targetStep: $targetStep,
  178. displayPickerTarget: $displayPickerTarget,
  179. toggleScrollWheel: toggleScrollWheel
  180. )
  181. }
  182. .onChange(of: target) {
  183. percentage = state.computeAdjustedPercentage(usingHBT: halfBasalTarget, usingTarget: target) * 100
  184. }
  185. }
  186. .listRowBackground(Color.chart)
  187. if target != state.normalTarget {
  188. let computedHalfBasalTarget = Decimal(
  189. state
  190. .computeHalfBasalTarget(usingTarget: target, usingPercentage: Double(percentage))
  191. )
  192. let sensHint = target > state.normalTarget ?
  193. "Reducing all delivered insulin to \(formattedPercentage(Double(percentage)))%." :
  194. "Increasing all delivered insulin by \(formattedPercentage(Double(percentage) - 100))%."
  195. if state.isAdjustSensEnabled(usingTarget: target) {
  196. Section(
  197. header: Text(sensHint)
  198. .textCase(.none)
  199. .foregroundStyle(colorScheme == .dark ? Color.orange : Color.accentColor),
  200. content: {
  201. VStack {
  202. Picker("Sensitivity Adjustment", selection: $tempTargetSensitivityAdjustmentType) {
  203. ForEach(TempTargetSensitivityAdjustmentType.allCases, id: \.self) { option in
  204. Text(option.rawValue).tag(option)
  205. }
  206. .pickerStyle(MenuPickerStyle())
  207. .onChange(of: tempTargetSensitivityAdjustmentType) { newValue in
  208. if newValue == .standard {
  209. halfBasalTarget = state.settingHalfBasalTarget
  210. hasChanges = true
  211. percentage = (
  212. state
  213. .computeAdjustedPercentage(usingHBT: halfBasalTarget, usingTarget: target) *
  214. 100
  215. )
  216. }
  217. }
  218. }
  219. if tempTargetSensitivityAdjustmentType == .slider {
  220. Text("\(formattedPercentage(Double(percentage))) % Insulin")
  221. .foregroundColor(isUsingSlider ? .orange : Color.tabBar)
  222. .font(.title3)
  223. .fontWeight(.bold)
  224. Slider(
  225. value: Binding(
  226. get: {
  227. Double(truncating: percentage as NSNumber)
  228. },
  229. set: { newValue in
  230. percentage = Decimal(newValue)
  231. hasChanges = true
  232. halfBasalTarget = Decimal(state.computeHalfBasalTarget(
  233. usingTarget: target,
  234. usingPercentage: Double(percentage)
  235. ))
  236. }
  237. ),
  238. in: state.computeSliderLow(usingTarget: target) ... state
  239. .computeSliderHigh(usingTarget: target) - 1,
  240. step: 5
  241. ) {}
  242. minimumValueLabel: {
  243. Text("\(state.computeSliderLow(usingTarget: target), specifier: "%.0f")%")
  244. }
  245. maximumValueLabel: {
  246. Text("\(state.computeSliderHigh(usingTarget: target), specifier: "%.0f")%")
  247. }
  248. Divider()
  249. HStack {
  250. Text(
  251. "Half Basal Exercise Target:"
  252. )
  253. Spacer()
  254. Text(formattedGlucose(glucose: computedHalfBasalTarget))
  255. }.foregroundStyle(.primary)
  256. }
  257. }
  258. .padding(.vertical, 10)
  259. }
  260. )
  261. .listRowBackground(Color.chart)
  262. .padding(.top, -10)
  263. }
  264. }
  265. }
  266. }
  267. private var saveButton: some View {
  268. HStack {
  269. Spacer()
  270. Button(action: {
  271. saveChanges()
  272. do {
  273. guard let moc = tempTarget.managedObjectContext else { return }
  274. guard moc.hasChanges else { return }
  275. try moc.save()
  276. if let currentActiveTempTarget = state.currentActiveTempTarget {
  277. Task {
  278. // TODO: - Creating a Run entry is probably needed for Overrides as well and the reason for "jumping" Overrides?
  279. // Disable previous active Temp Targets
  280. await state.disableAllActiveOverrides(
  281. except: currentActiveTempTarget.objectID,
  282. createOverrideRunEntry: false
  283. )
  284. // If the temp target which currently gets edited is enabled, then store it to the Temp Target JSON so that oref uses it
  285. if isEnabled {
  286. let tempTarget = TempTarget(
  287. name: name,
  288. createdAt: Date(),
  289. targetTop: target,
  290. targetBottom: target,
  291. duration: duration,
  292. enteredBy: TempTarget.manual,
  293. reason: TempTarget.custom,
  294. isPreset: isPreset ? true : false,
  295. enabled: isEnabled ? true : false,
  296. halfBasalTarget: halfBasalTarget
  297. )
  298. // Store to TempTargetStorage so that oref uses the edited Temp target
  299. state.saveTempTargetToStorage(tempTargets: [tempTarget])
  300. }
  301. // Update view
  302. state.updateLatestTempTargetConfiguration()
  303. }
  304. }
  305. hasChanges = false
  306. presentationMode.wrappedValue.dismiss()
  307. } catch {
  308. debugPrint("Failed to Edit Temp Target")
  309. }
  310. }, label: {
  311. Text("Save")
  312. })
  313. .disabled(!hasChanges)
  314. .frame(maxWidth: .infinity, alignment: .center)
  315. .tint(.white)
  316. Spacer()
  317. }.listRowBackground(hasChanges ? Color(.systemBlue) : Color(.systemGray4))
  318. }
  319. private func saveChanges() {
  320. tempTarget.name = name
  321. tempTarget.target = NSDecimalNumber(decimal: target)
  322. tempTarget.duration = NSDecimalNumber(decimal: duration)
  323. tempTarget.date = date
  324. tempTarget.isUploadedToNS = false
  325. tempTarget.halfBasalTarget = NSDecimalNumber(decimal: halfBasalTarget)
  326. }
  327. private func toggleScrollWheel(_ toggle: Bool) -> Bool {
  328. displayPickerDuration = false
  329. displayPickerTarget = false
  330. return !toggle
  331. }
  332. private func resetValues() {
  333. name = tempTarget.name ?? ""
  334. target = tempTarget.target?.decimalValue ?? 0
  335. duration = tempTarget.duration?.decimalValue ?? 0
  336. date = tempTarget.date ?? Date()
  337. }
  338. private func totalDurationInMinutes() -> Int {
  339. let durationTotal = (durationHours * 60) + durationMinutes
  340. return max(0, durationTotal)
  341. }
  342. private var formatter: NumberFormatter {
  343. let formatter = NumberFormatter()
  344. formatter.numberStyle = .decimal
  345. formatter.maximumFractionDigits = 0
  346. return formatter
  347. }
  348. private var glucoseFormatter: NumberFormatter {
  349. let formatter = NumberFormatter()
  350. formatter.numberStyle = .decimal
  351. if state.units == .mmolL {
  352. formatter.maximumFractionDigits = 1
  353. } else {
  354. formatter.maximumFractionDigits = 0
  355. }
  356. formatter.roundingMode = .halfUp
  357. return formatter
  358. }
  359. private func formattedPercentage(_ value: Double) -> String {
  360. let percentageNumber = NSNumber(value: value)
  361. return formatter.string(from: percentageNumber) ?? "\(value)"
  362. }
  363. private func formattedGlucose(glucose: Decimal) -> String {
  364. let formattedValue: String
  365. if state.units == .mgdL {
  366. formattedValue = glucoseFormatter.string(from: glucose as NSDecimalNumber) ?? "\(glucose)"
  367. } else {
  368. formattedValue = glucose.formattedAsMmolL
  369. }
  370. return "\(formattedValue) \(state.units.rawValue)"
  371. }
  372. }