TempTargetView.swift 13 KB

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