AddTempTargetForm.swift 19 KB

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