AddCarbPresetIntent.swift 2.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. import AppIntents
  2. import Foundation
  3. import Intents
  4. import Swinject
  5. @available(iOS 16.0,*) struct AddCarbPresentIntent: AppIntent {
  6. // Title of the action in the Shortcuts app
  7. static var title: LocalizedStringResource = "Add carbs"
  8. // Description of the action in the Shortcuts app
  9. static var description = IntentDescription("Allow to add carbs in iAPS.")
  10. internal var carbRequest: CarbPresetIntentRequest
  11. init() {
  12. carbRequest = CarbPresetIntentRequest()
  13. dateAdded = Date()
  14. }
  15. @Parameter(
  16. title: "Quantity Carbs",
  17. description: "Quantity of carbs in g",
  18. controlStyle: .field,
  19. inclusiveRange: (lowerBound: 0, upperBound: 200),
  20. requestValueDialog: IntentDialog("What is the numeric value of the carb to add")
  21. ) var carbQuantity: Double?
  22. @Parameter(
  23. title: "Quantity fat",
  24. description: "Quantity of fat in g",
  25. default: 0.0,
  26. inclusiveRange: (0, 200)
  27. ) var fatQuantity: Double
  28. @Parameter(
  29. title: "Quantity Protein",
  30. description: "Quantity of Protein in g",
  31. default: 0.0,
  32. inclusiveRange: (0, 200)
  33. ) var proteinQuantity: Double
  34. @Parameter(
  35. title: "Date",
  36. description: "Date of adding"
  37. ) var dateAdded: Date
  38. @Parameter(
  39. title: "Confirm Before applying",
  40. description: "If toggled, you will need to confirm before applying",
  41. default: true
  42. ) var confirmBeforeApplying: Bool
  43. static var parameterSummary: some ParameterSummary {
  44. When(\.$confirmBeforeApplying, .equalTo, true, {
  45. Summary("Applying \(\.$carbQuantity) at \(\.$dateAdded)") {
  46. \.$fatQuantity
  47. \.$proteinQuantity
  48. \.$confirmBeforeApplying
  49. }
  50. }, otherwise: {
  51. Summary("Immediately applying \(\.$carbQuantity) at \(\.$dateAdded)") {
  52. \.$fatQuantity
  53. \.$proteinQuantity
  54. \.$confirmBeforeApplying
  55. }
  56. })
  57. }
  58. @MainActor func perform() async throws -> some ProvidesDialog {
  59. do {
  60. let quantityCarbs: Double
  61. if let cq = carbQuantity {
  62. quantityCarbs = cq
  63. } else {
  64. quantityCarbs = try await $carbQuantity.requestValue("How many carbs ?")
  65. }
  66. let quantityCarbsName = quantityCarbs.toString()
  67. if confirmBeforeApplying {
  68. try await requestConfirmation(
  69. result: .result(dialog: "Are you sure to add \(quantityCarbsName) g of carbs ?")
  70. )
  71. }
  72. let finalQuantityCarbsDisplay = try await carbRequest.addCarbs(quantityCarbs, fatQuantity, proteinQuantity, dateAdded)
  73. return .result(
  74. dialog: IntentDialog(stringLiteral: finalQuantityCarbsDisplay)
  75. )
  76. } catch {
  77. throw error
  78. }
  79. }
  80. }