TrioNightscoutRemoteView.swift 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289
  1. //
  2. // TrioNightscoutRemoteView.swift
  3. // LoopFollow
  4. //
  5. // Created by Jonas Björkert on 2024-07-19.
  6. // Copyright © 2024 Jon Fawcett. All rights reserved.
  7. //
  8. import SwiftUI
  9. import HealthKit
  10. struct TrioNightscoutRemoteView: View {
  11. private let remoteController = TrioNightscoutRemoteController()
  12. @ObservedObject var nightscoutURL = ObservableUserDefaults.shared.url
  13. @ObservedObject var device = ObservableUserDefaults.shared.device
  14. @ObservedObject var nsWriteAuth = ObservableUserDefaults.shared.nsWriteAuth
  15. @ObservedObject var tempTarget = Observable.shared.tempTarget
  16. @State private var newHKTarget = HKQuantity(unit: .milligramsPerDeciliter, doubleValue: 0.0)
  17. @State private var duration = HKQuantity(unit: .minute(), doubleValue: 0.0)
  18. @State private var showAlert: Bool = false
  19. @State private var alertType: AlertType? = nil
  20. @State private var alertMessage: String? = nil
  21. @State private var isLoading: Bool = false
  22. @State private var statusMessage: String? = nil
  23. @State private var showPresetSheet: Bool = false
  24. @State private var presetName = ""
  25. @ObservedObject var presetManager = TempTargetPresetManager.shared
  26. @FocusState private var targetFieldIsFocused: Bool
  27. @FocusState private var durationFieldIsFocused: Bool
  28. enum AlertType {
  29. case confirmCommand
  30. case status
  31. case validation
  32. case confirmCancellation
  33. }
  34. var body: some View {
  35. NavigationView {
  36. VStack {
  37. if nightscoutURL.value.isEmpty {
  38. ErrorMessageView(
  39. message: "Remote commands are currently only available for Trio. It requires you to enter your Nightscout address and a token with the careportal role in the settings."
  40. )
  41. } else if device.value != "Trio" {
  42. ErrorMessageView(
  43. message: "Remote commands are currently only available for Trio."
  44. )
  45. } else if !nsWriteAuth.value {
  46. ErrorMessageView(
  47. message: "Please update your token to include the 'careportal' and 'readable' roles in order to do remote commands."
  48. )
  49. } else {
  50. Form {
  51. if let tempTargetValue = tempTarget.value {
  52. Section(header: Text("Existing Temp Target")) {
  53. HStack {
  54. Text("Current Target")
  55. Spacer()
  56. Text(Localizer.formatQuantity(tempTargetValue))
  57. Text(UserDefaultsRepository.getPreferredUnit().localizedShortUnitString).foregroundColor(.secondary)
  58. }
  59. Button {
  60. alertType = .confirmCancellation
  61. showAlert = true
  62. } label: {
  63. HStack {
  64. Text("Cancel Temp Target")
  65. Spacer()
  66. Image(systemName: "xmark.app")
  67. .font(.title)
  68. }
  69. }
  70. .tint(.red)
  71. }
  72. }
  73. Section(header: Text("Temporary Target")) {
  74. HStack {
  75. Text("Target")
  76. Spacer()
  77. TextFieldWithToolBar(
  78. quantity: $newHKTarget,
  79. maxLength: 4,
  80. unit: UserDefaultsRepository.getPreferredUnit(),
  81. minValue: HKQuantity(unit: .milligramsPerDeciliter, doubleValue: 60),
  82. maxValue: HKQuantity(unit: .milligramsPerDeciliter, doubleValue: 300),
  83. onValidationError: { message in
  84. handleValidationError(message)
  85. }
  86. )
  87. .focused($targetFieldIsFocused)
  88. Text(UserDefaultsRepository.getPreferredUnit().localizedShortUnitString).foregroundColor(.secondary)
  89. }
  90. HStack {
  91. Text("Duration")
  92. Spacer()
  93. TextFieldWithToolBar(
  94. quantity: $duration,
  95. maxLength: 4,
  96. unit: HKUnit.minute(),
  97. minValue: HKQuantity(unit: .minute(), doubleValue: 5),
  98. onValidationError: { message in
  99. handleValidationError(message)
  100. }
  101. )
  102. .focused($durationFieldIsFocused)
  103. Text("minutes").foregroundColor(.secondary)
  104. }
  105. HStack {
  106. Button {
  107. alertType = .confirmCommand
  108. showAlert = true
  109. targetFieldIsFocused = false
  110. durationFieldIsFocused = false
  111. } label: {
  112. Text("Enact")
  113. }
  114. .disabled(isButtonDisabled)
  115. .buttonStyle(BorderlessButtonStyle())
  116. .font(.callout)
  117. .controlSize(.mini)
  118. Spacer()
  119. Button {
  120. showPresetSheet = true
  121. targetFieldIsFocused = false
  122. durationFieldIsFocused = false
  123. } label: {
  124. Text("Save as Preset")
  125. }
  126. .disabled(isButtonDisabled)
  127. .buttonStyle(BorderlessButtonStyle())
  128. .font(.callout)
  129. .controlSize(.mini)
  130. }
  131. }
  132. if !presetManager.presets.isEmpty {
  133. Section(header: Text("Presets")) {
  134. ForEach(presetManager.presets) { preset in
  135. HStack {
  136. Text(preset.name)
  137. Spacer()
  138. }
  139. .contentShape(Rectangle())
  140. .onTapGesture {
  141. alertType = .confirmCommand
  142. newHKTarget = preset.target
  143. duration = preset.duration
  144. showAlert = true
  145. targetFieldIsFocused = false
  146. durationFieldIsFocused = false
  147. }
  148. .swipeActions {
  149. Button(role: .destructive) {
  150. if let index = presetManager.presets.firstIndex(where: { $0.id == preset.id }) {
  151. presetManager.deletePreset(at: index)
  152. }
  153. targetFieldIsFocused = false
  154. durationFieldIsFocused = false
  155. } label: {
  156. Label("Delete", systemImage: "trash")
  157. }
  158. }
  159. }
  160. }
  161. }
  162. }
  163. if isLoading {
  164. ProgressView("Please wait...")
  165. .padding()
  166. }
  167. }
  168. }
  169. .navigationTitle("Remote")
  170. .navigationBarTitleDisplayMode(.inline)
  171. .alert(isPresented: $showAlert) {
  172. switch alertType {
  173. case .confirmCommand:
  174. return Alert(
  175. title: Text("Confirm Command"),
  176. message: Text("New Target: \(Localizer.formatQuantity(newHKTarget)) \(UserDefaultsRepository.getPreferredUnit().localizedShortUnitString)\nDuration: \(Int(duration.doubleValue(for: HKUnit.minute()))) minutes"),
  177. primaryButton: .default(Text("Confirm"), action: {
  178. enactTempTarget()
  179. }),
  180. secondaryButton: .cancel()
  181. )
  182. case .status:
  183. return Alert(
  184. title: Text("Status"),
  185. message: Text(statusMessage ?? ""),
  186. dismissButton: .default(Text("OK"), action: {
  187. showAlert = false
  188. })
  189. )
  190. case .confirmCancellation:
  191. return Alert(
  192. title: Text("Confirm Cancellation"),
  193. message: Text("Are you sure you want to cancel the existing temp target?"),
  194. primaryButton: .default(Text("Confirm"), action: {
  195. cancelTempTarget()
  196. }),
  197. secondaryButton: .cancel()
  198. )
  199. case .validation:
  200. return Alert(
  201. title: Text("Validation Error"),
  202. message: Text(alertMessage ?? "Invalid input."),
  203. dismissButton: .default(Text("OK"))
  204. )
  205. case .none:
  206. return Alert(title: Text("Unknown Alert"))
  207. }
  208. }
  209. .sheet(isPresented: $showPresetSheet) {
  210. VStack {
  211. Text("Save Preset")
  212. .font(.headline)
  213. .padding()
  214. TextField("Preset Name", text: $presetName)
  215. .textFieldStyle(RoundedBorderTextFieldStyle())
  216. .padding()
  217. HStack {
  218. Button("Cancel") {
  219. showPresetSheet = false
  220. }
  221. .padding()
  222. Spacer()
  223. Button("Save") {
  224. presetManager.addPreset(name: presetName, target: newHKTarget, duration: duration)
  225. presetName = ""
  226. showPresetSheet = false
  227. }
  228. .disabled(presetName.isEmpty)
  229. .padding()
  230. }
  231. Spacer()
  232. }
  233. .padding()
  234. }
  235. }
  236. }
  237. private var isButtonDisabled: Bool {
  238. return newHKTarget.doubleValue(for: UserDefaultsRepository.getPreferredUnit()) == 0 ||
  239. duration.doubleValue(for: HKUnit.minute()) == 0 || isLoading
  240. }
  241. private func enactTempTarget() {
  242. isLoading = true
  243. remoteController.sendTempTarget(newTarget: newHKTarget, duration: duration) { success in
  244. self.isLoading = false
  245. if success {
  246. self.statusMessage = "Command successfully sent to Nightscout."
  247. } else {
  248. self.statusMessage = "Failed to enact target."
  249. }
  250. self.alertType = .status
  251. self.showAlert = true
  252. }
  253. }
  254. private func cancelTempTarget() {
  255. isLoading = true
  256. remoteController.cancelExistingTarget { success in
  257. self.isLoading = false
  258. if success {
  259. self.statusMessage = "Cancellation request successfully sent to Nightscout."
  260. } else {
  261. self.statusMessage = "Failed to cancel temp target."
  262. }
  263. self.alertType = .status
  264. self.showAlert = true
  265. }
  266. }
  267. private func handleValidationError(_ message: String) {
  268. alertMessage = message
  269. alertType = .validation
  270. showAlert = true
  271. }
  272. }