EditTempTargetForm.swift 18 KB

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