EditTempTargetForm.swift 18 KB

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