EditTempTargetForm.swift 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467
  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. @Environment(AppState.self) var appState
  8. @StateObject var state: Adjustments.StateModel
  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 = 1
  15. @State private var name: String
  16. @State private var target: Decimal
  17. @State private var duration: Decimal
  18. @State private var date: Date
  19. @State private var halfBasalTarget: Decimal?
  20. @State private var percentage: Double
  21. @State private var hasChanges = false
  22. @State private var showAlert = false
  23. @State private var isUsingSlider = false
  24. @State private var isPreset = false
  25. @State private var isEnabled = false
  26. init(tempTargetToEdit: TempTargetStored, state: Adjustments.StateModel) {
  27. tempTarget = tempTargetToEdit
  28. _state = StateObject(wrappedValue: state)
  29. _name = State(initialValue: tempTargetToEdit.name ?? "")
  30. _target = State(initialValue: tempTargetToEdit.target?.decimalValue ?? 0)
  31. _duration = State(initialValue: tempTargetToEdit.duration?.decimalValue ?? 0)
  32. _date = State(initialValue: tempTargetToEdit.date ?? Date())
  33. _halfBasalTarget = State(initialValue: tempTargetToEdit.halfBasalTarget?.decimalValue ?? state.settingHalfBasalTarget)
  34. _isPreset = State(initialValue: tempTargetToEdit.isPreset)
  35. _isEnabled = State(initialValue: tempTargetToEdit.enabled)
  36. let tempTargetHalfBasal: Decimal = (tempTargetToEdit.halfBasalTarget?.decimalValue) ?? state.settingHalfBasalTarget
  37. let H = tempTargetHalfBasal
  38. let T = tempTargetToEdit.target?.decimalValue ?? 100
  39. let calcPercentage = TempTargetCalculations.computeAdjustedPercentage(
  40. halfBasalTarget: H,
  41. target: T,
  42. autosensMax: state.autosensMax
  43. )
  44. _percentage = State(initialValue: calcPercentage)
  45. }
  46. private var dateFormatter: DateFormatter {
  47. let f = DateFormatter()
  48. f.dateStyle = .short
  49. f.timeStyle = .short
  50. return f
  51. }
  52. var body: some View {
  53. NavigationView {
  54. List {
  55. editTempTarget()
  56. saveButton
  57. }
  58. .listSectionSpacing(10)
  59. .padding(.top, 30)
  60. .ignoresSafeArea(edges: .top)
  61. .scrollContentBackground(.hidden)
  62. .background(appState.trioBackgroundColor(for: colorScheme))
  63. .navigationTitle("Edit Temp Target")
  64. .navigationBarTitleDisplayMode(.inline)
  65. .toolbar {
  66. ToolbarItem(placement: .topBarLeading) {
  67. Button(action: {
  68. presentationMode.wrappedValue.dismiss()
  69. }, label: {
  70. Text("Cancel")
  71. })
  72. }
  73. ToolbarItem(placement: .topBarTrailing) {
  74. Button(
  75. action: {
  76. state.isHelpSheetPresented.toggle()
  77. },
  78. label: {
  79. Image(systemName: "questionmark.circle")
  80. }
  81. )
  82. }
  83. }
  84. .onAppear {
  85. // Determine if this is a custom slider adjustment or a standard with auto-adjustment
  86. debug(
  87. .default,
  88. "checkStandardTT onAppear: halfBasalTarget=\(String(describing: halfBasalTarget)), settingHBT=\(state.settingHalfBasalTarget), percentage=\(percentage), target=\(target)"
  89. )
  90. if halfBasalTarget != nil,
  91. halfBasalTarget != state.settingHalfBasalTarget
  92. {
  93. // Check if this was an auto-adjusted standard TT:
  94. // If computeEffectiveHBT with nil stored HBT returns non-nil, settings HBT would produce <= 15%
  95. let isAutoAdjustedStandard = TempTargetCalculations.computeEffectiveHBT(
  96. tempTargetHalfBasalTarget: nil,
  97. settingHalfBasalTarget: state.settingHalfBasalTarget,
  98. target: target,
  99. autosensMax: state.autosensMax
  100. ) != nil
  101. debug(
  102. .default,
  103. "checkStandardTT onAppear: isAutoAdjustedStandard=\(isAutoAdjustedStandard)"
  104. )
  105. if !isAutoAdjustedStandard {
  106. tempTargetSensitivityAdjustmentType = .slider
  107. debug(.default, "checkStandardTT onAppear: Setting adjustment type to .slider")
  108. } else {
  109. debug(.default, "checkStandardTT onAppear: Keeping adjustment type as .standard (auto-adjusted)")
  110. }
  111. } else {
  112. debug(
  113. .default,
  114. "checkStandardTT onAppear: Keeping adjustment type as .standard (HBT is nil or matches settings)"
  115. )
  116. }
  117. }
  118. .sheet(isPresented: $state.isHelpSheetPresented) {
  119. TempTargetHelpView(state: state, helpSheetDetent: $state.helpSheetDetent)
  120. }
  121. }
  122. }
  123. private func calculatedEndDate(from startDate: Date, totalDuration: Decimal) -> Date {
  124. let elapsedTime = Date().timeIntervalSince(startDate)
  125. let totalDurationSeconds = Int(totalDuration) * 60
  126. let remainingTime = max(totalDurationSeconds - Int(elapsedTime), 0)
  127. return Date().addingTimeInterval(TimeInterval(remainingTime))
  128. }
  129. private func formattedEndTime(startDate: Date, totalDuration: Decimal) -> String {
  130. let endDate = calculatedEndDate(from: startDate, totalDuration: totalDuration)
  131. let formatter = DateFormatter()
  132. if Calendar.current.isDateInToday(endDate) {
  133. formatter.dateStyle = .none
  134. formatter.timeStyle = .short // show only the time
  135. } else {
  136. formatter.dateStyle = .short
  137. formatter.timeStyle = .short // show Date and time
  138. }
  139. return formatter.string(from: endDate)
  140. }
  141. @ViewBuilder private func editTempTarget() -> some View {
  142. Group {
  143. Section {
  144. HStack {
  145. Text("Name")
  146. Spacer()
  147. TextField("(Optional)", text: $name)
  148. .multilineTextAlignment(.trailing)
  149. .onChange(of: name) {
  150. hasChanges = true
  151. }
  152. }
  153. }.listRowBackground(Color.chart)
  154. Section {
  155. // Picker on the right side
  156. let settingsProvider = PickerSettingsProvider.shared
  157. let glucoseSetting = PickerSetting(value: 0, step: targetStep, min: 80, max: 200, type: .glucose)
  158. TargetPicker(
  159. label: "Target Glucose",
  160. selection: Binding(
  161. get: { target },
  162. set: { target = $0 }
  163. ),
  164. options: settingsProvider.generatePickerValues(
  165. from: glucoseSetting,
  166. units: state.units,
  167. roundMinToStep: true
  168. ),
  169. units: state.units,
  170. hasChanges: $hasChanges,
  171. targetStep: $targetStep,
  172. displayPickerTarget: $displayPickerTarget,
  173. toggleScrollWheel: toggleScrollWheel
  174. )
  175. .onChange(of: target) {
  176. // percentage = state.computeAdjustedPercentage(usingHBT: halfBasalTarget, usingTarget: target)
  177. // target value changes shall not alter the sensitivity, instead calculate new hbt with sensitivity from slider
  178. halfBasalTarget = Decimal(
  179. TempTargetCalculations
  180. .computeHalfBasalTarget(target: target, percentage: percentage)
  181. )
  182. }
  183. }
  184. .listRowBackground(Color.chart)
  185. if target != TempTargetCalculations.normalTarget {
  186. let computedHalfBasalTarget = Decimal(
  187. TempTargetCalculations.computeHalfBasalTarget(target: target, percentage: percentage)
  188. )
  189. if state.isAdjustSensEnabled(usingTarget: target) {
  190. Section(
  191. footer: state.percentageDescription(percentage),
  192. content: {
  193. Picker("Sensitivity Adjustment", selection: $tempTargetSensitivityAdjustmentType) {
  194. ForEach(TempTargetSensitivityAdjustmentType.allCases, id: \.self) { option in
  195. Text(option.rawValue).tag(option)
  196. }
  197. .pickerStyle(MenuPickerStyle())
  198. .onChange(of: tempTargetSensitivityAdjustmentType) { _, newValue in
  199. if newValue == .standard {
  200. halfBasalTarget = nil
  201. hasChanges = true
  202. percentage = TempTargetCalculations.computeAdjustedPercentage(
  203. halfBasalTarget: state.settingHalfBasalTarget,
  204. target: target,
  205. autosensMax: state.autosensMax
  206. )
  207. }
  208. }
  209. }
  210. Text("\(formattedPercentage(percentage))% Insulin")
  211. .foregroundColor(isUsingSlider ? .orange : Color.tabBar)
  212. .font(.title3)
  213. .fontWeight(.bold)
  214. .frame(maxWidth: .infinity, alignment: .center)
  215. if tempTargetSensitivityAdjustmentType == .slider {
  216. Slider(
  217. value: Binding(
  218. get: {
  219. Double(truncating: percentage as NSNumber)
  220. },
  221. set: { newValue in
  222. percentage = newValue
  223. hasChanges = true
  224. halfBasalTarget = Decimal(TempTargetCalculations.computeHalfBasalTarget(
  225. target: target,
  226. percentage: percentage
  227. ))
  228. }
  229. ),
  230. in: state.computeSliderLow(usingTarget: target) ... state
  231. .computeSliderHigh(usingTarget: target),
  232. step: 5
  233. ) {}
  234. minimumValueLabel: {
  235. Text("\(state.computeSliderLow(usingTarget: target), specifier: "%.0f")%")
  236. }
  237. maximumValueLabel: {
  238. Text("\(state.computeSliderHigh(usingTarget: target), specifier: "%.0f")%")
  239. }
  240. .listRowSeparator(.hidden, edges: .top)
  241. }
  242. }
  243. )
  244. .listRowBackground(Color.chart)
  245. }
  246. }
  247. Section {
  248. DatePicker("Start Time", selection: $date, in: Date.now...)
  249. .onChange(of: date) { hasChanges = true }
  250. }.listRowBackground(Color.chart)
  251. Section {
  252. VStack {
  253. HStack {
  254. Text("Duration")
  255. Spacer()
  256. Text(state.formatHoursAndMinutes(Int(duration)))
  257. .foregroundColor(!displayPickerDuration ? (duration > 0 ? .primary : .secondary) : .accentColor)
  258. .onTapGesture {
  259. displayPickerDuration = toggleScrollWheel(displayPickerDuration)
  260. }
  261. }
  262. if displayPickerDuration {
  263. HStack {
  264. Picker(
  265. selection: Binding(
  266. get: {
  267. Int(truncating: duration as NSNumber) / 60
  268. },
  269. set: {
  270. let minutes = Int(truncating: duration as NSNumber) % 60
  271. let totalMinutes = $0 * 60 + minutes
  272. duration = Decimal(totalMinutes)
  273. hasChanges = duration > 0 ? true : false // prevents the user from setting 0 min
  274. }
  275. ),
  276. label: Text("")
  277. ) {
  278. ForEach(0 ..< 24) { hour in
  279. Text("\(hour) hr").tag(hour)
  280. }
  281. }
  282. .pickerStyle(WheelPickerStyle())
  283. .frame(maxWidth: .infinity)
  284. Picker(
  285. selection: Binding(
  286. get: {
  287. Int(truncating: duration as NSNumber) %
  288. 60 // Convert Decimal to Int for modulus operation
  289. },
  290. set: {
  291. duration = Decimal((Int(truncating: duration as NSNumber) / 60) * 60 + $0)
  292. hasChanges = duration > 0 ? true : false
  293. }
  294. ),
  295. label: Text("")
  296. ) {
  297. ForEach(Array(stride(from: 0, through: 55, by: 5)), id: \.self) { minute in
  298. Text("\(minute) min").tag(minute)
  299. }
  300. }
  301. .pickerStyle(WheelPickerStyle())
  302. .frame(maxWidth: .infinity)
  303. }
  304. .listRowSeparator(.hidden, edges: .top)
  305. }
  306. }
  307. }.listRowBackground(Color.chart)
  308. if isEnabled {
  309. Section {
  310. HStack {
  311. Spacer()
  312. Text("Until \(formattedEndTime(startDate: date, totalDuration: duration))").foregroundStyle(.secondary)
  313. }
  314. }.listRowBackground(Color.clear)
  315. }
  316. }
  317. }
  318. private var saveButton: some View {
  319. HStack {
  320. Spacer()
  321. Button(action: {
  322. saveChanges()
  323. do {
  324. guard let moc = tempTarget.managedObjectContext else { return }
  325. guard moc.hasChanges else { return }
  326. try moc.save()
  327. if let currentActiveTempTarget = state.currentActiveTempTarget {
  328. Task {
  329. // TODO: - Creating a Run entry is probably needed for Overrides as well and the reason for "jumping" Overrides?
  330. // Disable previous active Temp Targets
  331. await state.disableAllActiveTempTargets(
  332. except: currentActiveTempTarget.objectID,
  333. createTempTargetRunEntry: false
  334. )
  335. // If the temp target which currently gets edited is enabled, then store it to the Temp Target JSON so that oref uses it
  336. if isEnabled {
  337. let tempTarget = TempTarget(
  338. name: name,
  339. createdAt: Date(),
  340. targetTop: target,
  341. targetBottom: target,
  342. duration: duration,
  343. enteredBy: TempTarget.local,
  344. reason: TempTarget.custom,
  345. isPreset: isPreset ? true : false,
  346. enabled: isEnabled ? true : false,
  347. halfBasalTarget: halfBasalTarget
  348. )
  349. // Store to TempTargetStorage so that oref uses the edited Temp target
  350. state.saveTempTargetToStorage(tempTargets: [tempTarget])
  351. }
  352. // Update view
  353. state.updateLatestTempTargetConfiguration()
  354. }
  355. }
  356. hasChanges = false
  357. presentationMode.wrappedValue.dismiss()
  358. } catch {
  359. debugPrint("Failed to Edit Temp Target")
  360. }
  361. }, label: {
  362. Text("Save")
  363. })
  364. .disabled(!hasChanges)
  365. .frame(maxWidth: .infinity, alignment: .center)
  366. .tint(.white)
  367. Spacer()
  368. }.listRowBackground(hasChanges ? Color(.systemBlue) : Color(.systemGray4))
  369. }
  370. private func saveChanges() {
  371. tempTarget.name = name
  372. tempTarget.target = NSDecimalNumber(decimal: target)
  373. tempTarget.duration = NSDecimalNumber(decimal: duration)
  374. tempTarget.date = date
  375. tempTarget.isUploadedToNS = false
  376. if let halfBasalValue = halfBasalTarget {
  377. tempTarget.halfBasalTarget = NSDecimalNumber(decimal: halfBasalValue)
  378. } else {
  379. tempTarget.halfBasalTarget = nil
  380. }
  381. }
  382. private func toggleScrollWheel(_ toggle: Bool) -> Bool {
  383. displayPickerDuration = false
  384. displayPickerTarget = false
  385. return !toggle
  386. }
  387. private func resetValues() {
  388. name = tempTarget.name ?? ""
  389. target = tempTarget.target?.decimalValue ?? 0
  390. duration = tempTarget.duration?.decimalValue ?? 0
  391. date = tempTarget.date ?? Date()
  392. }
  393. private func totalDurationInMinutes() -> Int {
  394. let durationTotal = (durationHours * 60) + durationMinutes
  395. return max(0, durationTotal)
  396. }
  397. private var formatter: NumberFormatter {
  398. let formatter = NumberFormatter()
  399. formatter.numberStyle = .decimal
  400. formatter.maximumFractionDigits = 0
  401. return formatter
  402. }
  403. private var glucoseFormatter: NumberFormatter {
  404. let formatter = NumberFormatter()
  405. formatter.numberStyle = .decimal
  406. if state.units == .mmolL {
  407. formatter.maximumFractionDigits = 1
  408. } else {
  409. formatter.maximumFractionDigits = 0
  410. }
  411. formatter.roundingMode = .halfUp
  412. return formatter
  413. }
  414. private func formattedPercentage(_ value: Double) -> String {
  415. let percentageNumber = NSNumber(value: value)
  416. return formatter.string(from: percentageNumber) ?? "\(value)"
  417. }
  418. private func formattedGlucose(glucose: Decimal) -> String {
  419. let formattedValue: String
  420. if state.units == .mgdL {
  421. formattedValue = glucoseFormatter.string(from: glucose as NSDecimalNumber) ?? "\(glucose)"
  422. } else {
  423. formattedValue = glucose.formattedAsMmolL
  424. }
  425. return "\(formattedValue) \(state.units.rawValue)"
  426. }
  427. }