AddTempTargetForm.swift 18 KB

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