TempTargetView.swift 13 KB

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