EditTempTargetForm.swift 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402
  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. // Picker on the right side
  161. let settingsProvider = PickerSettingsProvider.shared
  162. let glucoseSetting = PickerSetting(value: 0, step: targetStep, min: 80, max: 270, type: .glucose)
  163. TargetPicker(
  164. label: "Target Glucose",
  165. selection: Binding(
  166. get: { target },
  167. set: { target = $0 }
  168. ),
  169. options: settingsProvider.generatePickerValues(
  170. from: glucoseSetting,
  171. units: state.units,
  172. roundMinToStep: true
  173. ),
  174. units: state.units,
  175. hasChanges: $hasChanges,
  176. targetStep: $targetStep,
  177. displayPickerTarget: $displayPickerTarget,
  178. toggleScrollWheel: toggleScrollWheel
  179. )
  180. .onChange(of: target) {
  181. percentage = state.computeAdjustedPercentage(usingHBT: halfBasalTarget, usingTarget: target) * 100
  182. }
  183. }
  184. .listRowBackground(Color.chart)
  185. if target != state.normalTarget {
  186. let computedHalfBasalTarget = Decimal(
  187. state
  188. .computeHalfBasalTarget(usingTarget: target, usingPercentage: Double(percentage))
  189. )
  190. let sensHint = target > state.normalTarget ?
  191. "Reducing all delivered insulin to \(formattedPercentage(Double(percentage)))%." :
  192. "Increasing all delivered insulin by \(formattedPercentage(Double(percentage) - 100))%."
  193. if state.isAdjustSensEnabled(usingTarget: target) {
  194. Section(
  195. header: Text(sensHint)
  196. .textCase(.none)
  197. .foregroundStyle(colorScheme == .dark ? Color.orange : Color.accentColor),
  198. content: {
  199. VStack {
  200. Picker("Sensitivity Adjustment", selection: $tempTargetSensitivityAdjustmentType) {
  201. ForEach(TempTargetSensitivityAdjustmentType.allCases, id: \.self) { option in
  202. Text(option.rawValue).tag(option)
  203. }
  204. .pickerStyle(MenuPickerStyle())
  205. .onChange(of: tempTargetSensitivityAdjustmentType) { _, newValue in
  206. if newValue == .standard {
  207. halfBasalTarget = state.settingHalfBasalTarget
  208. hasChanges = true
  209. percentage = (
  210. state
  211. .computeAdjustedPercentage(usingHBT: halfBasalTarget, usingTarget: target) *
  212. 100
  213. )
  214. }
  215. }
  216. }
  217. if tempTargetSensitivityAdjustmentType == .slider {
  218. Text("\(formattedPercentage(Double(percentage))) % Insulin")
  219. .foregroundColor(isUsingSlider ? .orange : Color.tabBar)
  220. .font(.title3)
  221. .fontWeight(.bold)
  222. Slider(
  223. value: Binding(
  224. get: {
  225. Double(truncating: percentage as NSNumber)
  226. },
  227. set: { newValue in
  228. percentage = Decimal(newValue)
  229. hasChanges = true
  230. halfBasalTarget = Decimal(state.computeHalfBasalTarget(
  231. usingTarget: target,
  232. usingPercentage: Double(percentage)
  233. ))
  234. }
  235. ),
  236. in: state.computeSliderLow(usingTarget: target) ... state
  237. .computeSliderHigh(usingTarget: target) - 1,
  238. step: 5
  239. ) {}
  240. minimumValueLabel: {
  241. Text("\(state.computeSliderLow(usingTarget: target), specifier: "%.0f")%")
  242. }
  243. maximumValueLabel: {
  244. Text("\(state.computeSliderHigh(usingTarget: target), specifier: "%.0f")%")
  245. }
  246. Divider()
  247. HStack {
  248. Text(
  249. "Half Basal Exercise Target:"
  250. )
  251. Spacer()
  252. Text(formattedGlucose(glucose: computedHalfBasalTarget))
  253. }.foregroundStyle(.primary)
  254. }
  255. }
  256. .padding(.vertical, 10)
  257. }
  258. )
  259. .listRowBackground(Color.chart)
  260. .padding(.top, -10)
  261. }
  262. }
  263. }
  264. }
  265. private var saveButton: some View {
  266. HStack {
  267. Spacer()
  268. Button(action: {
  269. saveChanges()
  270. do {
  271. guard let moc = tempTarget.managedObjectContext else { return }
  272. guard moc.hasChanges else { return }
  273. try moc.save()
  274. if let currentActiveTempTarget = state.currentActiveTempTarget {
  275. Task {
  276. // TODO: - Creating a Run entry is probably needed for Overrides as well and the reason for "jumping" Overrides?
  277. // Disable previous active Temp Targets
  278. await state.disableAllActiveOverrides(
  279. except: currentActiveTempTarget.objectID,
  280. createOverrideRunEntry: false
  281. )
  282. // If the temp target which currently gets edited is enabled, then store it to the Temp Target JSON so that oref uses it
  283. if isEnabled {
  284. let tempTarget = TempTarget(
  285. name: name,
  286. createdAt: Date(),
  287. targetTop: target,
  288. targetBottom: target,
  289. duration: duration,
  290. enteredBy: TempTarget.manual,
  291. reason: TempTarget.custom,
  292. isPreset: isPreset ? true : false,
  293. enabled: isEnabled ? true : false,
  294. halfBasalTarget: halfBasalTarget
  295. )
  296. // Store to TempTargetStorage so that oref uses the edited Temp target
  297. state.saveTempTargetToStorage(tempTargets: [tempTarget])
  298. }
  299. // Update view
  300. state.updateLatestTempTargetConfiguration()
  301. }
  302. }
  303. hasChanges = false
  304. presentationMode.wrappedValue.dismiss()
  305. } catch {
  306. debugPrint("Failed to Edit Temp Target")
  307. }
  308. }, label: {
  309. Text("Save")
  310. })
  311. .disabled(!hasChanges)
  312. .frame(maxWidth: .infinity, alignment: .center)
  313. .tint(.white)
  314. Spacer()
  315. }.listRowBackground(hasChanges ? Color(.systemBlue) : Color(.systemGray4))
  316. }
  317. private func saveChanges() {
  318. tempTarget.name = name
  319. tempTarget.target = NSDecimalNumber(decimal: target)
  320. tempTarget.duration = NSDecimalNumber(decimal: duration)
  321. tempTarget.date = date
  322. tempTarget.isUploadedToNS = false
  323. tempTarget.halfBasalTarget = NSDecimalNumber(decimal: halfBasalTarget)
  324. }
  325. private func toggleScrollWheel(_ toggle: Bool) -> Bool {
  326. displayPickerDuration = false
  327. displayPickerTarget = false
  328. return !toggle
  329. }
  330. private func resetValues() {
  331. name = tempTarget.name ?? ""
  332. target = tempTarget.target?.decimalValue ?? 0
  333. duration = tempTarget.duration?.decimalValue ?? 0
  334. date = tempTarget.date ?? Date()
  335. }
  336. private func totalDurationInMinutes() -> Int {
  337. let durationTotal = (durationHours * 60) + durationMinutes
  338. return max(0, durationTotal)
  339. }
  340. private var formatter: NumberFormatter {
  341. let formatter = NumberFormatter()
  342. formatter.numberStyle = .decimal
  343. formatter.maximumFractionDigits = 0
  344. return formatter
  345. }
  346. private var glucoseFormatter: NumberFormatter {
  347. let formatter = NumberFormatter()
  348. formatter.numberStyle = .decimal
  349. if state.units == .mmolL {
  350. formatter.maximumFractionDigits = 1
  351. } else {
  352. formatter.maximumFractionDigits = 0
  353. }
  354. formatter.roundingMode = .halfUp
  355. return formatter
  356. }
  357. private func formattedPercentage(_ value: Double) -> String {
  358. let percentageNumber = NSNumber(value: value)
  359. return formatter.string(from: percentageNumber) ?? "\(value)"
  360. }
  361. private func formattedGlucose(glucose: Decimal) -> String {
  362. let formattedValue: String
  363. if state.units == .mgdL {
  364. formattedValue = glucoseFormatter.string(from: glucose as NSDecimalNumber) ?? "\(glucose)"
  365. } else {
  366. formattedValue = glucose.formattedAsMmolL
  367. }
  368. return "\(formattedValue) \(state.units.rawValue)"
  369. }
  370. }