GlucoseTargetsView.swift 5.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136
  1. import Charts
  2. import Foundation
  3. import SwiftUI
  4. struct GlucoseTargetsView: ChartContent {
  5. let startMarker: Date
  6. let units: GlucoseUnits
  7. let bgTargets: BGTargets
  8. var body: some ChartContent {
  9. drawGlucoseTargets()
  10. }
  11. /**
  12. Draws glucose target ranges on the chart
  13. - Returns: A ChartContent containing line marks representing target glucose ranges
  14. The function:
  15. - Creates target profiles for two consecutive days
  16. - Converts values between mg/dL and mmol/L based on user settings
  17. - Draws green lines to visualize the target ranges
  18. */
  19. private func drawGlucoseTargets() -> some ChartContent {
  20. // Array to store target profiles for visualization
  21. let targetProfiles: [TargetProfile] = processFetchedTargets(bgTargets)
  22. // Draw target lines for each profile
  23. return ForEach(targetProfiles, id: \.self) { profile in
  24. LineMark(
  25. x: .value("Time", Date(timeIntervalSinceReferenceDate: profile.startTime)),
  26. y: .value("Target", profile.value)
  27. )
  28. .lineStyle(.init(lineWidth: 1))
  29. .foregroundStyle(Color.green.gradient)
  30. LineMark(
  31. x: .value("Time", Date(timeIntervalSinceReferenceDate: profile.endTime)),
  32. y: .value("Target", profile.value)
  33. )
  34. .lineStyle(.init(lineWidth: 1))
  35. .foregroundStyle(Color.green.gradient)
  36. }
  37. }
  38. /**
  39. Processes raw glucose target data into a list of target profiles for visualization.
  40. - Parameter rawTargets: The raw glucose target data containing offset and glucose values.
  41. - Returns: An array of `TargetProfile` objects, each representing a glucose target range starting from the day of the startMarker and ending two days later.
  42. The function:
  43. - Converts glucose targets into profiles covering three consecutive days (day of startMarker, day after startMarker and day after that).
  44. - Calculates start and end times for each target based on the offsets provided.
  45. - Handles conversions between mg/dL and mmol/L as per user settings.
  46. - Ensures targets span across midnight to avoid data cutoff.
  47. */
  48. private func processFetchedTargets(_ rawTargets: BGTargets) -> [TargetProfile] {
  49. var targetProfiles: [TargetProfile] = []
  50. // Ensure there are targets to process
  51. guard !rawTargets.targets.isEmpty else {
  52. print("Warning: No targets to process in rawTargets.")
  53. return []
  54. }
  55. let targets = rawTargets.targets
  56. // Base date is the start of the day for the startMarker
  57. let baseDate = Calendar.current.startOfDay(for: startMarker)
  58. // Process each target three times
  59. for index in 0 ..< (targets.count * 3) {
  60. // Calculate the day offset (0 for today, 1 for tomorrow, 2 for day after)
  61. let dayOffset = index / targets.count
  62. let targetIndex = index % targets.count
  63. // Validate target index to ensure safety
  64. guard targetIndex < targets.count else {
  65. print("Error: Invalid target index \(targetIndex).")
  66. continue
  67. }
  68. // Fetch the target for the current iteration
  69. let target = targets[targetIndex]
  70. // Calculate the time offset for the current day
  71. let dayTimeOffset = TimeInterval(dayOffset * 24 * 60 * 60)
  72. // Calculate the start time for the current target
  73. let startTime = baseDate
  74. .addingTimeInterval(dayTimeOffset)
  75. .addingTimeInterval(TimeInterval(target.offset * 60))
  76. // Calculate the end time for the current target
  77. let endTime: Date = {
  78. if targetIndex + 1 < targets.count {
  79. // End time is the start time of the next target within the same day
  80. return baseDate
  81. .addingTimeInterval(dayTimeOffset)
  82. .addingTimeInterval(TimeInterval(targets[targetIndex + 1].offset * 60))
  83. } else {
  84. // End time is the end of the day (midnight of the next day)
  85. return baseDate.addingTimeInterval(dayTimeOffset + 24 * 60 * 60)
  86. }
  87. }()
  88. // Convert glucose value based on user unit preference (mg/dL or mmol/L)
  89. let targetValue = units == .mgdL ? target.low : target.low.asMmolL
  90. // Append the processed target profile to the list
  91. targetProfiles.append(
  92. TargetProfile(
  93. value: targetValue,
  94. startTime: startTime.timeIntervalSinceReferenceDate,
  95. endTime: endTime.timeIntervalSinceReferenceDate
  96. )
  97. )
  98. }
  99. return targetProfiles
  100. }
  101. }
  102. struct TargetProfile: Hashable {
  103. let value: Decimal
  104. let startTime: TimeInterval
  105. let endTime: TimeInterval
  106. }
  107. private extension Date {
  108. var startOfDay: Date {
  109. Calendar.current.startOfDay(for: self)
  110. }
  111. }