AddTempTargetForm.swift 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430
  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 isSliderEnabled: Bool {
  56. state.computeSliderHigh() > state.computeSliderLow()
  57. }
  58. var body: some View {
  59. NavigationView {
  60. List {
  61. addTempTarget()
  62. saveButton
  63. }
  64. .listSectionSpacing(10)
  65. .listRowSpacing(10)
  66. .padding(.top, 30)
  67. .ignoresSafeArea(edges: .top)
  68. .scrollContentBackground(.hidden).background(color)
  69. .navigationTitle("Add Temp Target")
  70. .navigationBarTitleDisplayMode(.inline)
  71. .toolbar {
  72. ToolbarItem(placement: .topBarLeading) {
  73. Button(action: {
  74. presentationMode.wrappedValue.dismiss()
  75. }, label: {
  76. Text("Cancel")
  77. })
  78. }
  79. }
  80. .sheet(isPresented: $shouldDisplayHint) {
  81. SettingInputHintView(
  82. hintDetent: $hintDetent,
  83. shouldDisplayHint: $shouldDisplayHint,
  84. hintLabel: hintLabel ?? "",
  85. hintText: selectedVerboseHint ?? "",
  86. sheetTitle: "Help"
  87. )
  88. }
  89. .onAppear { targetStep = state.units == .mgdL ? 5 : 9 }
  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 != 0 {
  193. let headerText = state
  194. .tempTargetTarget > 100 ?
  195. "Raised Sensitivity: Insulin reduced to \(formattedPercentage(state.percentage))% of regular amount." :
  196. "Lowered Sensitivity: Insulin increased to \(formattedPercentage(state.percentage))% of regular amount."
  197. Section(
  198. header: Text(headerText).textCase(.none)
  199. .foregroundStyle(colorScheme == .dark ? Color.orange : Color.accentColor),
  200. content: {
  201. VStack {
  202. Text("\(Int(state.percentage)) % Insulin")
  203. .foregroundColor(isUsingSlider ? .orange : Color.tabBar)
  204. .font(.title3)
  205. .fontWeight(.bold)
  206. Slider(
  207. value: $state.percentage,
  208. in: state.computeSliderLow() ... state.computeSliderHigh(),
  209. step: 5
  210. ) {} minimumValueLabel: {
  211. Text("\(state.computeSliderLow(), specifier: "%.0f")%")
  212. } maximumValueLabel: {
  213. Text("\(state.computeSliderHigh(), specifier: "%.0f")%")
  214. } onEditingChanged: { editing in
  215. isUsingSlider = editing
  216. state.halfBasalTarget = Decimal(state.computeHalfBasalTarget())
  217. }
  218. .disabled(!isSliderEnabled)
  219. Divider()
  220. HStack {
  221. Text(
  222. "Half Basal Exercise Target at: \(formattedGlucose(glucose: Decimal(state.computeHalfBasalTarget())))"
  223. )
  224. .lineLimit(1)
  225. .minimumScaleFactor(0.8)
  226. .foregroundColor(.secondary)
  227. Spacer()
  228. }
  229. }
  230. }
  231. ).listRowBackground(Color.chart)
  232. }
  233. }
  234. }
  235. private func isTempTargetInvalid() -> (Bool, String?) {
  236. let noDurationSpecified = state.tempTargetDuration == 0
  237. let targetZero = state.tempTargetTarget < 80
  238. if noDurationSpecified {
  239. return (true, "Set a duration!")
  240. }
  241. if targetZero {
  242. return (
  243. true,
  244. "\(state.units == .mgdL ? "80 " : "4.4 ")" + state.units.rawValue + " needed as min. Glucose Target!"
  245. )
  246. }
  247. return (false, nil)
  248. }
  249. private var saveButton: some View {
  250. let (isInvalid, errorMessage) = isTempTargetInvalid()
  251. let noNameSpecified = state.tempTargetName == ""
  252. return Group {
  253. Section(
  254. header:
  255. HStack {
  256. Spacer()
  257. Text(errorMessage ?? "").textCase(nil)
  258. .foregroundColor(colorScheme == .dark ? .orange : .accentColor)
  259. Spacer()
  260. },
  261. content: {
  262. Button(action: {
  263. Task {
  264. if noNameSpecified { state.tempTargetName = "Custom Target" }
  265. didPressSave.toggle()
  266. state.isTempTargetEnabled.toggle()
  267. await state.saveCustomTempTarget()
  268. await state.resetTempTargetState()
  269. dismiss()
  270. }
  271. }, label: {
  272. Text("Enact Temp Target")
  273. })
  274. .disabled(isInvalid)
  275. .frame(maxWidth: .infinity, alignment: .center)
  276. .tint(.white)
  277. }
  278. ).listRowBackground(isInvalid ? Color(.systemGray4) : Color(.systemBlue))
  279. Section {
  280. Button(action: {
  281. Task {
  282. if noNameSpecified { state.tempTargetName = "Custom Target" }
  283. didPressSave.toggle()
  284. await state.saveTempTargetPreset()
  285. dismiss()
  286. }
  287. }, label: {
  288. Text("Save as Preset")
  289. })
  290. .disabled(isInvalid)
  291. .frame(maxWidth: .infinity, alignment: .center)
  292. .tint(.white)
  293. }
  294. .listRowBackground(
  295. isInvalid ? Color(.systemGray4) : Color.secondary
  296. )
  297. }
  298. }
  299. private func totalDurationInMinutes() -> Int {
  300. let durationTotal = (durationHours * 60) + durationMinutes
  301. return max(0, durationTotal)
  302. }
  303. private func formattedPercentage(_ value: Double) -> String {
  304. let percentageNumber = NSNumber(value: value)
  305. return formatter.string(from: percentageNumber) ?? "\(value)"
  306. }
  307. private func formattedGlucose(glucose: Decimal) -> String {
  308. let formattedValue: String
  309. if state.units == .mgdL {
  310. formattedValue = glucoseFormatter.string(from: glucose as NSDecimalNumber) ?? "\(glucose)"
  311. } else {
  312. formattedValue = glucose.formattedAsMmolL
  313. }
  314. return "\(formattedValue) \(state.units.rawValue)"
  315. }
  316. private func roundTargetToStep(_ target: Decimal, _ step: Decimal) -> Decimal {
  317. // Convert target and step to NSDecimalNumber
  318. guard let targetValue = NSDecimalNumber(decimal: target).doubleValue as Double?,
  319. let stepValue = NSDecimalNumber(decimal: step).doubleValue as Double?
  320. else {
  321. print("Failed to unwrap target or step as NSDecimalNumber")
  322. return target
  323. }
  324. // Perform the remainder check using truncatingRemainder
  325. let remainder = Decimal(targetValue.truncatingRemainder(dividingBy: stepValue))
  326. if remainder != 0 {
  327. // Calculate how much to adjust (up or down) based on the remainder
  328. let adjustment = step - remainder
  329. return target + adjustment
  330. }
  331. // Return the original target if no adjustment is needed
  332. return target
  333. }
  334. func generateTargetPickerValues() -> [Decimal] {
  335. var values: [Decimal] = []
  336. var currentValue: Double = 80 // lowest allowed TT in oref
  337. let step = Double(targetStep)
  338. // Adjust currentValue to be divisible by targetStep
  339. let remainder = currentValue.truncatingRemainder(dividingBy: step)
  340. if remainder != 0 {
  341. // Move currentValue up to the next value divisible by targetStep
  342. currentValue += (step - remainder)
  343. }
  344. // Now generate the picker values starting from currentValue
  345. while currentValue <= 270 {
  346. values.append(Decimal(currentValue))
  347. currentValue += step
  348. }
  349. // Glucose values are stored as mg/dl values, so Integers.
  350. // Filter out duplicate values when rounded to 1 decimal place.
  351. if state.units == .mmolL {
  352. // Use a Set to track unique values rounded to 1 decimal
  353. var uniqueRoundedValues = Set<String>()
  354. values = values.filter { value in
  355. let roundedValue = String(format: "%.1f", NSDecimalNumber(decimal: value.asMmolL).doubleValue)
  356. return uniqueRoundedValues.insert(roundedValue).inserted
  357. }
  358. }
  359. return values
  360. }
  361. }
  362. func formatHrMin(_ durationInMinutes: Int) -> String {
  363. let hours = durationInMinutes / 60
  364. let minutes = durationInMinutes % 60
  365. switch (hours, minutes) {
  366. case let (0, m):
  367. return "\(m) min"
  368. case let (h, 0):
  369. return "\(h) hr"
  370. default:
  371. return "\(hours) hr \(minutes) min"
  372. }
  373. }
  374. struct RadioButton: View {
  375. var isSelected: Bool
  376. var label: String
  377. var action: () -> Void
  378. var body: some View {
  379. Button(action: {
  380. action()
  381. }) {
  382. HStack {
  383. Image(systemName: isSelected ? "largecircle.fill.circle" : "circle")
  384. Text(label) // Add label inside the button to make it tappable
  385. }
  386. }
  387. .buttonStyle(PlainButtonStyle())
  388. }
  389. }