EditTempTargetForm.swift 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424
  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. ToolbarItem(placement: .topBarTrailing) {
  70. Button(
  71. action: {
  72. state.isHelpSheetPresented.toggle()
  73. },
  74. label: {
  75. Image(systemName: "questionmark.circle")
  76. }
  77. )
  78. }
  79. }
  80. .onAppear {
  81. if halfBasalTarget != state.settingHalfBasalTarget { tempTargetSensitivityAdjustmentType = .slider }
  82. }
  83. .sheet(isPresented: $state.isHelpSheetPresented) {
  84. TempTargetHelpView(state: state, helpSheetDetent: $state.helpSheetDetent)
  85. }
  86. }
  87. }
  88. private func calculatedEndDate(from startDate: Date, totalDuration: Decimal) -> Date {
  89. let elapsedTime = Date().timeIntervalSince(startDate)
  90. let totalDurationSeconds = Int(totalDuration) * 60
  91. let remainingTime = max(totalDurationSeconds - Int(elapsedTime), 0)
  92. return Date().addingTimeInterval(TimeInterval(remainingTime))
  93. }
  94. private func formattedEndTime(startDate: Date, totalDuration: Decimal) -> String {
  95. let endDate = calculatedEndDate(from: startDate, totalDuration: totalDuration)
  96. let formatter = DateFormatter()
  97. if Calendar.current.isDateInToday(endDate) {
  98. formatter.dateStyle = .none
  99. formatter.timeStyle = .short // show only the time
  100. } else {
  101. formatter.dateStyle = .short
  102. formatter.timeStyle = .short // show Date and time
  103. }
  104. return formatter.string(from: endDate)
  105. }
  106. @ViewBuilder private func editTempTarget() -> some View {
  107. Group {
  108. Section {
  109. HStack {
  110. Text("Name")
  111. Spacer()
  112. TextField("(Optional)", text: $name)
  113. .multilineTextAlignment(.trailing)
  114. .onChange(of: name) {
  115. hasChanges = true
  116. }
  117. }
  118. }.listRowBackground(Color.chart)
  119. Section {
  120. // Picker on the right side
  121. let settingsProvider = PickerSettingsProvider.shared
  122. let glucoseSetting = PickerSetting(value: 0, step: targetStep, min: 80, max: 200, type: .glucose)
  123. TargetPicker(
  124. label: "Target Glucose",
  125. selection: Binding(
  126. get: { target },
  127. set: { target = $0 }
  128. ),
  129. options: settingsProvider.generatePickerValues(
  130. from: glucoseSetting,
  131. units: state.units,
  132. roundMinToStep: true
  133. ),
  134. units: state.units,
  135. hasChanges: $hasChanges,
  136. targetStep: $targetStep,
  137. displayPickerTarget: $displayPickerTarget,
  138. toggleScrollWheel: toggleScrollWheel
  139. )
  140. .onChange(of: target) {
  141. percentage = state.computeAdjustedPercentage(usingHBT: halfBasalTarget, usingTarget: target)
  142. }
  143. }
  144. .listRowBackground(Color.chart)
  145. if target != state.normalTarget {
  146. let computedHalfBasalTarget = Decimal(
  147. state
  148. .computeHalfBasalTarget(usingTarget: target, usingPercentage: percentage)
  149. )
  150. if state.isAdjustSensEnabled(usingTarget: target) {
  151. Section(
  152. footer: state.percentageDescription(percentage),
  153. content: {
  154. Picker("Sensitivity Adjustment", selection: $tempTargetSensitivityAdjustmentType) {
  155. ForEach(TempTargetSensitivityAdjustmentType.allCases, id: \.self) { option in
  156. Text(option.rawValue).tag(option)
  157. }
  158. .pickerStyle(MenuPickerStyle())
  159. .onChange(of: tempTargetSensitivityAdjustmentType) { _, newValue in
  160. if newValue == .standard {
  161. halfBasalTarget = nil
  162. hasChanges = true
  163. percentage = state.computeAdjustedPercentage(
  164. usingHBT: halfBasalTarget,
  165. usingTarget: target
  166. )
  167. }
  168. }
  169. }
  170. Text("\(formattedPercentage(percentage))% Insulin")
  171. .foregroundColor(isUsingSlider ? .orange : Color.tabBar)
  172. .font(.title3)
  173. .fontWeight(.bold)
  174. .frame(maxWidth: .infinity, alignment: .center)
  175. if tempTargetSensitivityAdjustmentType == .slider {
  176. Slider(
  177. value: Binding(
  178. get: {
  179. Double(truncating: percentage as NSNumber)
  180. },
  181. set: { newValue in
  182. percentage = newValue
  183. hasChanges = true
  184. halfBasalTarget = Decimal(state.computeHalfBasalTarget(
  185. usingTarget: target,
  186. usingPercentage: percentage
  187. ))
  188. }
  189. ),
  190. in: state.computeSliderLow(usingTarget: target) ... state
  191. .computeSliderHigh(usingTarget: target),
  192. step: 5
  193. ) {}
  194. minimumValueLabel: {
  195. Text("\(state.computeSliderLow(usingTarget: target), specifier: "%.0f")%")
  196. }
  197. maximumValueLabel: {
  198. Text("\(state.computeSliderHigh(usingTarget: target), specifier: "%.0f")%")
  199. }
  200. .listRowSeparator(.hidden, edges: .top)
  201. }
  202. }
  203. )
  204. .listRowBackground(Color.chart)
  205. }
  206. }
  207. Section {
  208. DatePicker("Start Time", selection: $date, in: Date.now...)
  209. .onChange(of: date) { hasChanges = true }
  210. }.listRowBackground(Color.chart)
  211. Section {
  212. VStack {
  213. HStack {
  214. Text("Duration")
  215. Spacer()
  216. Text(state.formatHrMin(Int(duration)))
  217. .foregroundColor(!displayPickerDuration ? (duration > 0 ? .primary : .secondary) : .accentColor)
  218. .onTapGesture {
  219. displayPickerDuration = toggleScrollWheel(displayPickerDuration)
  220. }
  221. }
  222. if displayPickerDuration {
  223. HStack {
  224. Picker(
  225. selection: Binding(
  226. get: {
  227. Int(truncating: duration as NSNumber) / 60
  228. },
  229. set: {
  230. let minutes = Int(truncating: duration as NSNumber) % 60
  231. let totalMinutes = $0 * 60 + minutes
  232. duration = Decimal(totalMinutes)
  233. hasChanges = duration > 0 ? true : false // prevents the user from setting 0 min
  234. }
  235. ),
  236. label: Text("")
  237. ) {
  238. ForEach(0 ..< 24) { hour in
  239. Text("\(hour) hr").tag(hour)
  240. }
  241. }
  242. .pickerStyle(WheelPickerStyle())
  243. .frame(maxWidth: .infinity)
  244. Picker(
  245. selection: Binding(
  246. get: {
  247. Int(truncating: duration as NSNumber) %
  248. 60 // Convert Decimal to Int for modulus operation
  249. },
  250. set: {
  251. duration = Decimal((Int(truncating: duration as NSNumber) / 60) * 60 + $0)
  252. hasChanges = duration > 0 ? true : false
  253. }
  254. ),
  255. label: Text("")
  256. ) {
  257. ForEach(Array(stride(from: 0, through: 55, by: 5)), id: \.self) { minute in
  258. Text("\(minute) min").tag(minute)
  259. }
  260. }
  261. .pickerStyle(WheelPickerStyle())
  262. .frame(maxWidth: .infinity)
  263. }
  264. .listRowSeparator(.hidden, edges: .top)
  265. }
  266. }
  267. }.listRowBackground(Color.chart)
  268. if isEnabled {
  269. Section {
  270. HStack {
  271. Spacer()
  272. Text("Until \(formattedEndTime(startDate: date, totalDuration: duration))").foregroundStyle(.secondary)
  273. }
  274. }.listRowBackground(Color.clear)
  275. }
  276. }
  277. }
  278. private var saveButton: some View {
  279. HStack {
  280. Spacer()
  281. Button(action: {
  282. saveChanges()
  283. do {
  284. guard let moc = tempTarget.managedObjectContext else { return }
  285. guard moc.hasChanges else { return }
  286. try moc.save()
  287. if let currentActiveTempTarget = state.currentActiveTempTarget {
  288. Task {
  289. // TODO: - Creating a Run entry is probably needed for Overrides as well and the reason for "jumping" Overrides?
  290. // Disable previous active Temp Targets
  291. await state.disableAllActiveOverrides(
  292. except: currentActiveTempTarget.objectID,
  293. createOverrideRunEntry: false
  294. )
  295. // If the temp target which currently gets edited is enabled, then store it to the Temp Target JSON so that oref uses it
  296. if isEnabled {
  297. let tempTarget = TempTarget(
  298. name: name,
  299. createdAt: Date(),
  300. targetTop: target,
  301. targetBottom: target,
  302. duration: duration,
  303. enteredBy: TempTarget.local,
  304. reason: TempTarget.custom,
  305. isPreset: isPreset ? true : false,
  306. enabled: isEnabled ? true : false,
  307. halfBasalTarget: halfBasalTarget
  308. )
  309. // Store to TempTargetStorage so that oref uses the edited Temp target
  310. state.saveTempTargetToStorage(tempTargets: [tempTarget])
  311. }
  312. // Update view
  313. state.updateLatestTempTargetConfiguration()
  314. }
  315. }
  316. hasChanges = false
  317. presentationMode.wrappedValue.dismiss()
  318. } catch {
  319. debugPrint("Failed to Edit Temp Target")
  320. }
  321. }, label: {
  322. Text("Save")
  323. })
  324. .disabled(!hasChanges)
  325. .frame(maxWidth: .infinity, alignment: .center)
  326. .tint(.white)
  327. Spacer()
  328. }.listRowBackground(hasChanges ? Color(.systemBlue) : Color(.systemGray4))
  329. }
  330. private func saveChanges() {
  331. tempTarget.name = name
  332. tempTarget.target = NSDecimalNumber(decimal: target)
  333. tempTarget.duration = NSDecimalNumber(decimal: duration)
  334. tempTarget.date = date
  335. tempTarget.isUploadedToNS = false
  336. if let halfBasalValue = halfBasalTarget {
  337. tempTarget.halfBasalTarget = NSDecimalNumber(decimal: halfBasalValue)
  338. } else {
  339. tempTarget.halfBasalTarget = nil
  340. }
  341. }
  342. private func toggleScrollWheel(_ toggle: Bool) -> Bool {
  343. displayPickerDuration = false
  344. displayPickerTarget = false
  345. return !toggle
  346. }
  347. private func resetValues() {
  348. name = tempTarget.name ?? ""
  349. target = tempTarget.target?.decimalValue ?? 0
  350. duration = tempTarget.duration?.decimalValue ?? 0
  351. date = tempTarget.date ?? Date()
  352. }
  353. private func totalDurationInMinutes() -> Int {
  354. let durationTotal = (durationHours * 60) + durationMinutes
  355. return max(0, durationTotal)
  356. }
  357. private var formatter: NumberFormatter {
  358. let formatter = NumberFormatter()
  359. formatter.numberStyle = .decimal
  360. formatter.maximumFractionDigits = 0
  361. return formatter
  362. }
  363. private var glucoseFormatter: NumberFormatter {
  364. let formatter = NumberFormatter()
  365. formatter.numberStyle = .decimal
  366. if state.units == .mmolL {
  367. formatter.maximumFractionDigits = 1
  368. } else {
  369. formatter.maximumFractionDigits = 0
  370. }
  371. formatter.roundingMode = .halfUp
  372. return formatter
  373. }
  374. private func formattedPercentage(_ value: Double) -> String {
  375. let percentageNumber = NSNumber(value: value)
  376. return formatter.string(from: percentageNumber) ?? "\(value)"
  377. }
  378. private func formattedGlucose(glucose: Decimal) -> String {
  379. let formattedValue: String
  380. if state.units == .mgdL {
  381. formattedValue = glucoseFormatter.string(from: glucose as NSDecimalNumber) ?? "\(glucose)"
  382. } else {
  383. formattedValue = glucose.formattedAsMmolL
  384. }
  385. return "\(formattedValue) \(state.units.rawValue)"
  386. }
  387. }