EditTempTargetForm.swift 18 KB

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