EditTempTargetForm.swift 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411
  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 = state.computeAdjustedPercentage(usingHBT: H, usingTarget: T)
  40. _percentage = State(initialValue: calcPercentage)
  41. }
  42. private var dateFormatter: DateFormatter {
  43. let f = DateFormatter()
  44. f.dateStyle = .short
  45. f.timeStyle = .short
  46. return f
  47. }
  48. var body: some View {
  49. NavigationView {
  50. List {
  51. editTempTarget()
  52. saveButton
  53. }
  54. .listSectionSpacing(10)
  55. .padding(.top, 30)
  56. .ignoresSafeArea(edges: .top)
  57. .scrollContentBackground(.hidden)
  58. .background(appState.trioBackgroundColor(for: colorScheme))
  59. .navigationTitle("Edit Temp Target")
  60. .navigationBarTitleDisplayMode(.inline)
  61. .toolbar {
  62. ToolbarItem(placement: .topBarLeading) {
  63. Button(action: {
  64. presentationMode.wrappedValue.dismiss()
  65. }, label: {
  66. Text("Cancel")
  67. })
  68. }
  69. }
  70. .onAppear {
  71. if halfBasalTarget != state.settingHalfBasalTarget { tempTargetSensitivityAdjustmentType = .slider }
  72. }
  73. }
  74. }
  75. private func calculatedEndDate(from startDate: Date, totalDuration: Decimal) -> Date {
  76. let elapsedTime = Date().timeIntervalSince(startDate)
  77. let totalDurationSeconds = Int(totalDuration) * 60
  78. let remainingTime = max(totalDurationSeconds - Int(elapsedTime), 0)
  79. return Date().addingTimeInterval(TimeInterval(remainingTime))
  80. }
  81. private func formattedEndTime(startDate: Date, totalDuration: Decimal) -> String {
  82. let endDate = calculatedEndDate(from: startDate, totalDuration: totalDuration)
  83. let formatter = DateFormatter()
  84. if Calendar.current.isDateInToday(endDate) {
  85. formatter.dateStyle = .none
  86. formatter.timeStyle = .short // show only the time
  87. } else {
  88. formatter.dateStyle = .short
  89. formatter.timeStyle = .short // show Date and time
  90. }
  91. return formatter.string(from: endDate)
  92. }
  93. @ViewBuilder private func editTempTarget() -> some View {
  94. Group {
  95. Section {
  96. HStack {
  97. Text("Name")
  98. Spacer()
  99. TextField("(Optional)", text: $name)
  100. .multilineTextAlignment(.trailing)
  101. .onChange(of: name) {
  102. hasChanges = true
  103. }
  104. }
  105. }.listRowBackground(Color.chart)
  106. Section {
  107. // Picker on the right side
  108. let settingsProvider = PickerSettingsProvider.shared
  109. let glucoseSetting = PickerSetting(value: 0, step: targetStep, min: 80, max: 200, type: .glucose)
  110. TargetPicker(
  111. label: "Target Glucose",
  112. selection: Binding(
  113. get: { target },
  114. set: { target = $0 }
  115. ),
  116. options: settingsProvider.generatePickerValues(
  117. from: glucoseSetting,
  118. units: state.units,
  119. roundMinToStep: true
  120. ),
  121. units: state.units,
  122. hasChanges: $hasChanges,
  123. targetStep: $targetStep,
  124. displayPickerTarget: $displayPickerTarget,
  125. toggleScrollWheel: toggleScrollWheel
  126. )
  127. .onChange(of: target) {
  128. percentage = state.computeAdjustedPercentage(usingHBT: halfBasalTarget, usingTarget: target)
  129. }
  130. }
  131. .listRowBackground(Color.chart)
  132. if target != state.normalTarget {
  133. let computedHalfBasalTarget = Decimal(
  134. state
  135. .computeHalfBasalTarget(usingTarget: target, usingPercentage: percentage)
  136. )
  137. if state.isAdjustSensEnabled(usingTarget: target) {
  138. Section(
  139. footer: state.percentageDescription(percentage),
  140. content: {
  141. Picker("Sensitivity Adjustment", selection: $tempTargetSensitivityAdjustmentType) {
  142. ForEach(TempTargetSensitivityAdjustmentType.allCases, id: \.self) { option in
  143. Text(option.rawValue).tag(option)
  144. }
  145. .pickerStyle(MenuPickerStyle())
  146. .onChange(of: tempTargetSensitivityAdjustmentType) { _, newValue in
  147. if newValue == .standard {
  148. halfBasalTarget = nil
  149. hasChanges = true
  150. percentage = state.computeAdjustedPercentage(
  151. usingHBT: halfBasalTarget,
  152. usingTarget: target
  153. )
  154. }
  155. }
  156. }
  157. Text("\(formattedPercentage(percentage))% Insulin")
  158. .foregroundColor(isUsingSlider ? .orange : Color.tabBar)
  159. .font(.title3)
  160. .fontWeight(.bold)
  161. .frame(maxWidth: .infinity, alignment: .center)
  162. if tempTargetSensitivityAdjustmentType == .slider {
  163. Slider(
  164. value: Binding(
  165. get: {
  166. Double(truncating: percentage as NSNumber)
  167. },
  168. set: { newValue in
  169. percentage = newValue
  170. hasChanges = true
  171. halfBasalTarget = Decimal(state.computeHalfBasalTarget(
  172. usingTarget: target,
  173. usingPercentage: percentage
  174. ))
  175. }
  176. ),
  177. in: state.computeSliderLow(usingTarget: target) ... state
  178. .computeSliderHigh(usingTarget: target),
  179. step: 5
  180. ) {}
  181. minimumValueLabel: {
  182. Text("\(state.computeSliderLow(usingTarget: target), specifier: "%.0f")%")
  183. }
  184. maximumValueLabel: {
  185. Text("\(state.computeSliderHigh(usingTarget: target), specifier: "%.0f")%")
  186. }
  187. .listRowSeparator(.hidden, edges: .top)
  188. }
  189. }
  190. )
  191. .listRowBackground(Color.chart)
  192. }
  193. }
  194. Section {
  195. DatePicker("Start Time", selection: $date, in: Date.now...)
  196. .onChange(of: date) { hasChanges = true }
  197. }.listRowBackground(Color.chart)
  198. Section {
  199. VStack {
  200. HStack {
  201. Text("Duration")
  202. Spacer()
  203. Text(state.formatHrMin(Int(duration)))
  204. .foregroundColor(!displayPickerDuration ? (duration > 0 ? .primary : .secondary) : .accentColor)
  205. }
  206. .onTapGesture {
  207. displayPickerDuration = toggleScrollWheel(displayPickerDuration)
  208. }
  209. if displayPickerDuration {
  210. HStack {
  211. Picker(
  212. selection: Binding(
  213. get: {
  214. Int(truncating: duration as NSNumber) / 60
  215. },
  216. set: {
  217. let minutes = Int(truncating: duration as NSNumber) % 60
  218. let totalMinutes = $0 * 60 + minutes
  219. duration = Decimal(totalMinutes)
  220. hasChanges = duration > 0 ? true : false // prevents the user from setting 0 min
  221. }
  222. ),
  223. label: Text("")
  224. ) {
  225. ForEach(0 ..< 24) { hour in
  226. Text("\(hour) hr").tag(hour)
  227. }
  228. }
  229. .pickerStyle(WheelPickerStyle())
  230. .frame(maxWidth: .infinity)
  231. Picker(
  232. selection: Binding(
  233. get: {
  234. Int(truncating: duration as NSNumber) %
  235. 60 // Convert Decimal to Int for modulus operation
  236. },
  237. set: {
  238. duration = Decimal((Int(truncating: duration as NSNumber) / 60) * 60 + $0)
  239. hasChanges = duration > 0 ? true : false
  240. }
  241. ),
  242. label: Text("")
  243. ) {
  244. ForEach(Array(stride(from: 0, through: 55, by: 5)), id: \.self) { minute in
  245. Text("\(minute) min").tag(minute)
  246. }
  247. }
  248. .pickerStyle(WheelPickerStyle())
  249. .frame(maxWidth: .infinity)
  250. }
  251. .listRowSeparator(.hidden, edges: .top)
  252. }
  253. }
  254. }.listRowBackground(Color.chart)
  255. if isEnabled {
  256. Section {
  257. HStack {
  258. Spacer()
  259. Text("Until \(formattedEndTime(startDate: date, totalDuration: duration))").foregroundStyle(.secondary)
  260. }
  261. }.listRowBackground(Color.clear)
  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.local,
  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. if let halfBasalValue = halfBasalTarget {
  324. tempTarget.halfBasalTarget = NSDecimalNumber(decimal: halfBasalValue)
  325. } else {
  326. tempTarget.halfBasalTarget = nil
  327. }
  328. }
  329. private func toggleScrollWheel(_ toggle: Bool) -> Bool {
  330. displayPickerDuration = false
  331. displayPickerTarget = false
  332. return !toggle
  333. }
  334. private func resetValues() {
  335. name = tempTarget.name ?? ""
  336. target = tempTarget.target?.decimalValue ?? 0
  337. duration = tempTarget.duration?.decimalValue ?? 0
  338. date = tempTarget.date ?? Date()
  339. }
  340. private func totalDurationInMinutes() -> Int {
  341. let durationTotal = (durationHours * 60) + durationMinutes
  342. return max(0, durationTotal)
  343. }
  344. private var formatter: NumberFormatter {
  345. let formatter = NumberFormatter()
  346. formatter.numberStyle = .decimal
  347. formatter.maximumFractionDigits = 0
  348. return formatter
  349. }
  350. private var glucoseFormatter: NumberFormatter {
  351. let formatter = NumberFormatter()
  352. formatter.numberStyle = .decimal
  353. if state.units == .mmolL {
  354. formatter.maximumFractionDigits = 1
  355. } else {
  356. formatter.maximumFractionDigits = 0
  357. }
  358. formatter.roundingMode = .halfUp
  359. return formatter
  360. }
  361. private func formattedPercentage(_ value: Double) -> String {
  362. let percentageNumber = NSNumber(value: value)
  363. return formatter.string(from: percentageNumber) ?? "\(value)"
  364. }
  365. private func formattedGlucose(glucose: Decimal) -> String {
  366. let formattedValue: String
  367. if state.units == .mgdL {
  368. formattedValue = glucoseFormatter.string(from: glucose as NSDecimalNumber) ?? "\(glucose)"
  369. } else {
  370. formattedValue = glucose.formattedAsMmolL
  371. }
  372. return "\(formattedValue) \(state.units.rawValue)"
  373. }
  374. }