AddTempTargetForm.swift 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476
  1. import Foundation
  2. import SwiftUI
  3. struct AddTempTargetForm: View {
  4. @StateObject var state: OverrideConfig.StateModel
  5. @Environment(\.presentationMode) var presentationMode
  6. @Environment(\.colorScheme) var colorScheme
  7. @Environment(\.dismiss) var dismiss
  8. @State private var displayPickerDuration: Bool = false
  9. @State private var selectedAdjustSens: enabledAdjustSens = .standard
  10. @State private var durationHours = 0
  11. @State private var durationMinutes = 0
  12. @State private var targetStep: Decimal = 5
  13. @State private var displayPickerTarget: Bool = false
  14. @State private var showAlert = false
  15. @State private var showPresetAlert = false
  16. @State private var alertString = ""
  17. @State private var isUsingSlider = false
  18. @State private var didPressSave =
  19. false // only used for fixing the Disclaimer showing up after pressing save (after the state was resetted), maybe refactor this...
  20. @State private var shouldDisplayHint = false
  21. @State var hintDetent = PresentationDetent.large
  22. @State var selectedVerboseHint: String?
  23. @State var hintLabel: String?
  24. var isCustomizedAdjustSens: Bool = false
  25. var color: LinearGradient {
  26. colorScheme == .dark ? LinearGradient(
  27. gradient: Gradient(colors: [
  28. Color.bgDarkBlue,
  29. Color.bgDarkerDarkBlue
  30. ]),
  31. startPoint: .top,
  32. endPoint: .bottom
  33. )
  34. :
  35. LinearGradient(
  36. gradient: Gradient(colors: [Color.gray.opacity(0.1)]),
  37. startPoint: .top,
  38. endPoint: .bottom
  39. )
  40. }
  41. private var formatter: NumberFormatter {
  42. let formatter = NumberFormatter()
  43. formatter.numberStyle = .decimal
  44. formatter.maximumFractionDigits = 0
  45. return formatter
  46. }
  47. private var glucoseFormatter: NumberFormatter {
  48. let formatter = NumberFormatter()
  49. formatter.numberStyle = .decimal
  50. formatter.maximumFractionDigits = 0
  51. if state.units == .mmolL {
  52. formatter.maximumFractionDigits = 1
  53. }
  54. formatter.roundingMode = .halfUp
  55. return formatter
  56. }
  57. var body: some View {
  58. NavigationView {
  59. List {
  60. addTempTarget()
  61. saveButton
  62. }
  63. .listSectionSpacing(10)
  64. .listRowSpacing(10)
  65. .padding(.top, 30)
  66. .ignoresSafeArea(edges: .top)
  67. .scrollContentBackground(.hidden).background(color)
  68. .navigationTitle("Add Temp Target")
  69. .navigationBarTitleDisplayMode(.inline)
  70. .toolbar {
  71. ToolbarItem(placement: .topBarLeading) {
  72. Button(action: {
  73. presentationMode.wrappedValue.dismiss()
  74. }, label: {
  75. Text("Cancel")
  76. })
  77. }
  78. }
  79. .sheet(isPresented: $shouldDisplayHint) {
  80. SettingInputHintView(
  81. hintDetent: $hintDetent,
  82. shouldDisplayHint: $shouldDisplayHint,
  83. hintLabel: hintLabel ?? "",
  84. hintText: selectedVerboseHint ?? "",
  85. sheetTitle: "Help"
  86. )
  87. }
  88. .onAppear {
  89. targetStep = state.units == .mgdL ? 5 : 9
  90. state.tempTargetTarget = state.normalTarget
  91. }
  92. }
  93. }
  94. @ViewBuilder private func addTempTarget() -> some View {
  95. Group {
  96. Section {
  97. HStack {
  98. Text("Name")
  99. Spacer()
  100. TextField("(Optional)", text: $state.tempTargetName)
  101. .multilineTextAlignment(.trailing)
  102. }
  103. }.listRowBackground(Color.chart)
  104. Section {
  105. DatePicker("Date", selection: $state.date)
  106. }.listRowBackground(Color.chart)
  107. Section {
  108. VStack {
  109. HStack {
  110. Text("Duration")
  111. Spacer()
  112. Text(formatHrMin(Int(state.tempTargetDuration)))
  113. .foregroundColor(!displayPickerDuration ? .primary : .accentColor)
  114. }
  115. .onTapGesture {
  116. displayPickerDuration.toggle()
  117. }
  118. if displayPickerDuration {
  119. HStack {
  120. Picker("Hours", selection: $durationHours) {
  121. ForEach(0 ..< 24) { hour in
  122. Text("\(hour) hr").tag(hour)
  123. }
  124. }
  125. .pickerStyle(WheelPickerStyle())
  126. .frame(maxWidth: .infinity)
  127. .onChange(of: durationHours) {
  128. state.tempTargetDuration = Decimal(totalDurationInMinutes())
  129. }
  130. Picker("Minutes", selection: $durationMinutes) {
  131. ForEach(Array(stride(from: 0, through: 55, by: 5)), id: \.self) { minute in
  132. Text("\(minute) min").tag(minute)
  133. }
  134. }
  135. .pickerStyle(WheelPickerStyle())
  136. .frame(maxWidth: .infinity)
  137. .onChange(of: durationMinutes) {
  138. state.tempTargetDuration = Decimal(totalDurationInMinutes())
  139. }
  140. }
  141. }
  142. }
  143. }.listRowBackground(Color.chart)
  144. Section {
  145. HStack {
  146. Text("Target Glucose")
  147. Spacer()
  148. Text(formattedGlucose(glucose: state.tempTargetTarget))
  149. .foregroundColor(!displayPickerTarget ? .primary : .accentColor)
  150. }
  151. .onTapGesture {
  152. displayPickerTarget.toggle()
  153. }
  154. if displayPickerTarget {
  155. HStack {
  156. // Radio buttons and text on the left side
  157. VStack(alignment: .leading) {
  158. // Radio buttons for step iteration
  159. let stepChoices: [Decimal] = state.units == .mgdL ? [1, 5] : [1, 9]
  160. ForEach(stepChoices, id: \.self) { step in
  161. RadioButton(
  162. isSelected: targetStep == step,
  163. label: "\(state.units == .mgdL ? step : step.asMmolL) \(state.units.rawValue)"
  164. ) {
  165. targetStep = step
  166. state.tempTargetTarget = roundTargetToStep(state.tempTargetTarget, targetStep)
  167. }
  168. .padding(.top, 10)
  169. }
  170. }
  171. .frame(maxWidth: .infinity)
  172. Spacer()
  173. // Picker on the right side
  174. Picker(selection: Binding(
  175. get: { roundTargetToStep(state.tempTargetTarget, targetStep) },
  176. set: { state.tempTargetTarget = $0 }
  177. ), label: Text("")) {
  178. ForEach(
  179. generateTargetPickerValues(),
  180. id: \.self
  181. ) { glucose in
  182. Text(formattedGlucose(glucose: glucose))
  183. .tag(glucose)
  184. }
  185. }
  186. .pickerStyle(WheelPickerStyle())
  187. .frame(maxWidth: .infinity)
  188. .onChange(of: state.tempTargetTarget) {
  189. state.percentage = Double(state.computeAdjustedPercentage() * 100)
  190. }
  191. }
  192. }
  193. }.listRowBackground(Color.chart)
  194. if state.tempTargetTarget != state.normalTarget {
  195. let computedHalfBasalTarget = Decimal(state.computeHalfBasalTarget())
  196. if state.isAdjustSensEnabled() {
  197. Section(
  198. header: HStack {
  199. if state.tempTargetTarget > state.normalTarget {
  200. VStack(alignment: .leading) {
  201. HStack(spacing: 5) {
  202. Text("Sensitivity")
  203. Image(systemName: "arrow.up.circle")
  204. Text("Insulin")
  205. Image(systemName: "arrow.down.circle")
  206. }
  207. Text("Reducing all delivered insulin to \(formattedPercentage(state.percentage))%.")
  208. }
  209. }
  210. if state.tempTargetTarget < state.normalTarget {
  211. VStack(alignment: .leading) {
  212. HStack(spacing: 5) {
  213. Text("Sensitivity")
  214. Image(systemName: "arrow.down.circle")
  215. Text("Insulin")
  216. Image(systemName: "arrow.up.circle")
  217. }
  218. Text(
  219. "Increasing all delivered insulin by \(formattedPercentage(state.percentage - 100))%."
  220. )
  221. }
  222. }
  223. }
  224. .textCase(.none)
  225. .foregroundStyle(colorScheme == .dark ? Color.orange : Color.accentColor),
  226. content: {
  227. VStack {
  228. Picker("Sensitivity Adjustment", selection: $selectedAdjustSens) {
  229. ForEach(enabledAdjustSens.allCases, id: \.self) { option in
  230. Text(option.rawValue).tag(option)
  231. }
  232. .pickerStyle(MenuPickerStyle())
  233. .onChange(of: selectedAdjustSens) { newValue in
  234. if newValue == .standard {
  235. state.halfBasalTarget = state.settingHalfBasalTarget
  236. state.percentage = Double(state.computeAdjustedPercentage() * 100)
  237. }
  238. }
  239. }
  240. if selectedAdjustSens == .slider {
  241. Text("\(Int(state.percentage)) % Insulin")
  242. .foregroundColor(isUsingSlider ? .orange : Color.tabBar)
  243. .font(.title3)
  244. .fontWeight(.bold)
  245. Slider(
  246. value: $state.percentage,
  247. in: state.computeSliderLow() ... state.computeSliderHigh(),
  248. step: 5
  249. ) {} minimumValueLabel: {
  250. Text("\(state.computeSliderLow(), specifier: "%.0f")%")
  251. } maximumValueLabel: {
  252. Text("\(state.computeSliderHigh(), specifier: "%.0f")%")
  253. } onEditingChanged: { editing in
  254. isUsingSlider = editing
  255. state.halfBasalTarget = Decimal(state.computeHalfBasalTarget())
  256. }
  257. Divider()
  258. HStack {
  259. Text(
  260. "Half Basal Exercise Target:"
  261. )
  262. Spacer()
  263. Text(formattedGlucose(glucose: computedHalfBasalTarget))
  264. }.foregroundStyle(.primary)
  265. }
  266. }.padding(.vertical, 10)
  267. }
  268. )
  269. .listRowBackground(Color.chart)
  270. .padding(.top, -10)
  271. }
  272. }
  273. }
  274. }
  275. private func isTempTargetInvalid() -> (Bool, String?) {
  276. let noDurationSpecified = state.tempTargetDuration == 0
  277. let targetZero = state.tempTargetTarget < 80
  278. if noDurationSpecified {
  279. return (true, "Set a duration!")
  280. }
  281. if targetZero {
  282. return (
  283. true,
  284. "\(state.units == .mgdL ? "80 " : "4.4 ")" + state.units.rawValue + " needed as min. Glucose Target!"
  285. )
  286. }
  287. return (false, nil)
  288. }
  289. private var saveButton: some View {
  290. let (isInvalid, errorMessage) = isTempTargetInvalid()
  291. let noNameSpecified = state.tempTargetName == ""
  292. return Group {
  293. Section(
  294. header:
  295. HStack {
  296. Spacer()
  297. Text(errorMessage ?? "").textCase(nil)
  298. .foregroundColor(colorScheme == .dark ? .orange : .accentColor)
  299. Spacer()
  300. },
  301. content: {
  302. Button(action: {
  303. Task {
  304. if noNameSpecified { state.tempTargetName = "Custom Target" }
  305. didPressSave.toggle()
  306. state.isTempTargetEnabled.toggle()
  307. await state.saveCustomTempTarget()
  308. await state.resetTempTargetState()
  309. dismiss()
  310. }
  311. }, label: {
  312. Text("Enact Temp Target")
  313. })
  314. .disabled(isInvalid)
  315. .frame(maxWidth: .infinity, alignment: .center)
  316. .tint(.white)
  317. }
  318. ).listRowBackground(isInvalid ? Color(.systemGray4) : Color(.systemBlue))
  319. Section {
  320. Button(action: {
  321. Task {
  322. if noNameSpecified { state.tempTargetName = "Custom Target" }
  323. didPressSave.toggle()
  324. await state.saveTempTargetPreset()
  325. dismiss()
  326. }
  327. }, label: {
  328. Text("Save as Preset")
  329. })
  330. .disabled(isInvalid)
  331. .frame(maxWidth: .infinity, alignment: .center)
  332. .tint(.white)
  333. }
  334. .listRowBackground(
  335. isInvalid ? Color(.systemGray4) : Color.secondary
  336. )
  337. }
  338. }
  339. enum enabledAdjustSens: String, CaseIterable {
  340. case standard = "default"
  341. case slider = "customized"
  342. }
  343. private func totalDurationInMinutes() -> Int {
  344. let durationTotal = (durationHours * 60) + durationMinutes
  345. return max(0, durationTotal)
  346. }
  347. private func formattedPercentage(_ value: Double) -> String {
  348. let percentageNumber = NSNumber(value: value)
  349. return formatter.string(from: percentageNumber) ?? "\(value)"
  350. }
  351. private func formattedGlucose(glucose: Decimal) -> String {
  352. let formattedValue: String
  353. if state.units == .mgdL {
  354. formattedValue = glucoseFormatter.string(from: glucose as NSDecimalNumber) ?? "\(glucose)"
  355. } else {
  356. formattedValue = glucose.formattedAsMmolL
  357. }
  358. return "\(formattedValue) \(state.units.rawValue)"
  359. }
  360. private func roundTargetToStep(_ target: Decimal, _ step: Decimal) -> Decimal {
  361. // Convert target and step to NSDecimalNumber
  362. guard let targetValue = NSDecimalNumber(decimal: target).doubleValue as Double?,
  363. let stepValue = NSDecimalNumber(decimal: step).doubleValue as Double?
  364. else {
  365. print("Failed to unwrap target or step as NSDecimalNumber")
  366. return target
  367. }
  368. // Perform the remainder check using truncatingRemainder
  369. let remainder = Decimal(targetValue.truncatingRemainder(dividingBy: stepValue))
  370. if remainder != 0 {
  371. // Calculate how much to adjust (up or down) based on the remainder
  372. let adjustment = step - remainder
  373. return target + adjustment
  374. }
  375. // Return the original target if no adjustment is needed
  376. return target
  377. }
  378. func generateTargetPickerValues() -> [Decimal] {
  379. var values: [Decimal] = []
  380. var currentValue: Double = 80 // lowest allowed TT in oref
  381. let step = Double(targetStep)
  382. // Adjust currentValue to be divisible by targetStep
  383. let remainder = currentValue.truncatingRemainder(dividingBy: step)
  384. if remainder != 0 {
  385. // Move currentValue up to the next value divisible by targetStep
  386. currentValue += (step - remainder)
  387. }
  388. // Now generate the picker values starting from currentValue
  389. while currentValue <= 270 {
  390. values.append(Decimal(currentValue))
  391. currentValue += step
  392. }
  393. // Glucose values are stored as mg/dl values, so Integers.
  394. // Filter out duplicate values when rounded to 1 decimal place.
  395. if state.units == .mmolL {
  396. // Use a Set to track unique values rounded to 1 decimal
  397. var uniqueRoundedValues = Set<String>()
  398. values = values.filter { value in
  399. let roundedValue = String(format: "%.1f", NSDecimalNumber(decimal: value.asMmolL).doubleValue)
  400. return uniqueRoundedValues.insert(roundedValue).inserted
  401. }
  402. }
  403. return values
  404. }
  405. }
  406. func formatHrMin(_ durationInMinutes: Int) -> String {
  407. let hours = durationInMinutes / 60
  408. let minutes = durationInMinutes % 60
  409. switch (hours, minutes) {
  410. case let (0, m):
  411. return "\(m) min"
  412. case let (h, 0):
  413. return "\(h) hr"
  414. default:
  415. return "\(hours) hr \(minutes) min"
  416. }
  417. }
  418. struct RadioButton: View {
  419. var isSelected: Bool
  420. var label: String
  421. var action: () -> Void
  422. var body: some View {
  423. Button(action: {
  424. action()
  425. }) {
  426. HStack {
  427. Image(systemName: isSelected ? "largecircle.fill.circle" : "circle")
  428. Text(label) // Add label inside the button to make it tappable
  429. }
  430. }
  431. .buttonStyle(PlainButtonStyle())
  432. }
  433. }