AddTempTargetForm.swift 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471
  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 = state.computeHalfBasalTarget()
  196. if state.isAdjustSensEnabled() {
  197. Section(
  198. header: HStack {
  199. if state
  200. .tempTargetTarget > state.normalTarget
  201. {
  202. HStack(spacing: 5) {
  203. Text("Sensitivity")
  204. Image(systemName: "arrow.up.circle")
  205. Text("Insulin")
  206. Image(systemName: "arrow.down.circle")
  207. Text("using \(formattedPercentage(state.percentage))% of default.")
  208. }
  209. }
  210. if state.tempTargetTarget < state.normalTarget {
  211. HStack(spacing: 5) {
  212. Text("Sensitivity")
  213. Image(systemName: "arrow.down.circle")
  214. Text("Insulin")
  215. Image(systemName: "arrow.up.circle")
  216. Text("using \(formattedPercentage(state.percentage))% of default.")
  217. }
  218. }
  219. }
  220. .textCase(.none)
  221. .foregroundStyle(colorScheme == .dark ? Color.orange : Color.accentColor),
  222. content: {
  223. VStack {
  224. Picker("Sensitivity Adjustment", selection: $selectedAdjustSens) {
  225. ForEach(enabledAdjustSens.allCases, id: \.self) { option in
  226. Text(option.rawValue).tag(option)
  227. }
  228. }
  229. .pickerStyle(MenuPickerStyle())
  230. if selectedAdjustSens == .slider {
  231. Text("\(Int(state.percentage)) % Insulin")
  232. .foregroundColor(isUsingSlider ? .orange : Color.tabBar)
  233. .font(.title3)
  234. .fontWeight(.bold)
  235. Slider(
  236. value: $state.percentage,
  237. in: state.computeSliderLow() ... state.computeSliderHigh(),
  238. step: 5
  239. ) {} minimumValueLabel: {
  240. Text("\(state.computeSliderLow(), specifier: "%.0f")%")
  241. } maximumValueLabel: {
  242. Text("\(state.computeSliderHigh(), specifier: "%.0f")%")
  243. } onEditingChanged: { editing in
  244. isUsingSlider = editing
  245. state.halfBasalTarget = Decimal(state.computeHalfBasalTarget())
  246. }
  247. Divider()
  248. HStack {
  249. Text(
  250. "Half Basal Exercise Target:"
  251. )
  252. Spacer()
  253. Text(
  254. (
  255. state.units == .mgdL ? computedHalfBasalTarget
  256. .description : computedHalfBasalTarget
  257. .formattedAsMmolL
  258. ) + " " + state.units.rawValue
  259. )
  260. }.foregroundStyle(.primary)
  261. }
  262. }.padding(.vertical, 10)
  263. }
  264. )
  265. .listRowBackground(Color.chart)
  266. .padding(.top, -10)
  267. }
  268. }
  269. }
  270. }
  271. private func isTempTargetInvalid() -> (Bool, String?) {
  272. let noDurationSpecified = state.tempTargetDuration == 0
  273. let targetZero = state.tempTargetTarget < 80
  274. if noDurationSpecified {
  275. return (true, "Set a duration!")
  276. }
  277. if targetZero {
  278. return (
  279. true,
  280. "\(state.units == .mgdL ? "80 " : "4.4 ")" + state.units.rawValue + " needed as min. Glucose Target!"
  281. )
  282. }
  283. return (false, nil)
  284. }
  285. private var saveButton: some View {
  286. let (isInvalid, errorMessage) = isTempTargetInvalid()
  287. let noNameSpecified = state.tempTargetName == ""
  288. return Group {
  289. Section(
  290. header:
  291. HStack {
  292. Spacer()
  293. Text(errorMessage ?? "").textCase(nil)
  294. .foregroundColor(colorScheme == .dark ? .orange : .accentColor)
  295. Spacer()
  296. },
  297. content: {
  298. Button(action: {
  299. Task {
  300. if noNameSpecified { state.tempTargetName = "Custom Target" }
  301. didPressSave.toggle()
  302. state.isTempTargetEnabled.toggle()
  303. await state.saveCustomTempTarget()
  304. await state.resetTempTargetState()
  305. dismiss()
  306. }
  307. }, label: {
  308. Text("Enact Temp Target")
  309. })
  310. .disabled(isInvalid)
  311. .frame(maxWidth: .infinity, alignment: .center)
  312. .tint(.white)
  313. }
  314. ).listRowBackground(isInvalid ? Color(.systemGray4) : Color(.systemBlue))
  315. Section {
  316. Button(action: {
  317. Task {
  318. if noNameSpecified { state.tempTargetName = "Custom Target" }
  319. didPressSave.toggle()
  320. await state.saveTempTargetPreset()
  321. dismiss()
  322. }
  323. }, label: {
  324. Text("Save as Preset")
  325. })
  326. .disabled(isInvalid)
  327. .frame(maxWidth: .infinity, alignment: .center)
  328. .tint(.white)
  329. }
  330. .listRowBackground(
  331. isInvalid ? Color(.systemGray4) : Color.secondary
  332. )
  333. }
  334. }
  335. enum enabledAdjustSens: String, CaseIterable {
  336. case standard = "default"
  337. case slider = "customized"
  338. }
  339. private func totalDurationInMinutes() -> Int {
  340. let durationTotal = (durationHours * 60) + durationMinutes
  341. return max(0, durationTotal)
  342. }
  343. private func formattedPercentage(_ value: Double) -> String {
  344. let percentageNumber = NSNumber(value: value)
  345. return formatter.string(from: percentageNumber) ?? "\(value)"
  346. }
  347. private func formattedGlucose(glucose: Decimal) -> String {
  348. let formattedValue: String
  349. if state.units == .mgdL {
  350. formattedValue = glucoseFormatter.string(from: glucose as NSDecimalNumber) ?? "\(glucose)"
  351. } else {
  352. formattedValue = glucose.formattedAsMmolL
  353. }
  354. return "\(formattedValue) \(state.units.rawValue)"
  355. }
  356. private func roundTargetToStep(_ target: Decimal, _ step: Decimal) -> Decimal {
  357. // Convert target and step to NSDecimalNumber
  358. guard let targetValue = NSDecimalNumber(decimal: target).doubleValue as Double?,
  359. let stepValue = NSDecimalNumber(decimal: step).doubleValue as Double?
  360. else {
  361. print("Failed to unwrap target or step as NSDecimalNumber")
  362. return target
  363. }
  364. // Perform the remainder check using truncatingRemainder
  365. let remainder = Decimal(targetValue.truncatingRemainder(dividingBy: stepValue))
  366. if remainder != 0 {
  367. // Calculate how much to adjust (up or down) based on the remainder
  368. let adjustment = step - remainder
  369. return target + adjustment
  370. }
  371. // Return the original target if no adjustment is needed
  372. return target
  373. }
  374. func generateTargetPickerValues() -> [Decimal] {
  375. var values: [Decimal] = []
  376. var currentValue: Double = 80 // lowest allowed TT in oref
  377. let step = Double(targetStep)
  378. // Adjust currentValue to be divisible by targetStep
  379. let remainder = currentValue.truncatingRemainder(dividingBy: step)
  380. if remainder != 0 {
  381. // Move currentValue up to the next value divisible by targetStep
  382. currentValue += (step - remainder)
  383. }
  384. // Now generate the picker values starting from currentValue
  385. while currentValue <= 270 {
  386. values.append(Decimal(currentValue))
  387. currentValue += step
  388. }
  389. // Glucose values are stored as mg/dl values, so Integers.
  390. // Filter out duplicate values when rounded to 1 decimal place.
  391. if state.units == .mmolL {
  392. // Use a Set to track unique values rounded to 1 decimal
  393. var uniqueRoundedValues = Set<String>()
  394. values = values.filter { value in
  395. let roundedValue = String(format: "%.1f", NSDecimalNumber(decimal: value.asMmolL).doubleValue)
  396. return uniqueRoundedValues.insert(roundedValue).inserted
  397. }
  398. }
  399. return values
  400. }
  401. }
  402. func formatHrMin(_ durationInMinutes: Int) -> String {
  403. let hours = durationInMinutes / 60
  404. let minutes = durationInMinutes % 60
  405. switch (hours, minutes) {
  406. case let (0, m):
  407. return "\(m) min"
  408. case let (h, 0):
  409. return "\(h) hr"
  410. default:
  411. return "\(hours) hr \(minutes) min"
  412. }
  413. }
  414. struct RadioButton: View {
  415. var isSelected: Bool
  416. var label: String
  417. var action: () -> Void
  418. var body: some View {
  419. Button(action: {
  420. action()
  421. }) {
  422. HStack {
  423. Image(systemName: isSelected ? "largecircle.fill.circle" : "circle")
  424. Text(label) // Add label inside the button to make it tappable
  425. }
  426. }
  427. .buttonStyle(PlainButtonStyle())
  428. }
  429. }