EditTempTargetForm.swift 17 KB

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