MealStatsSetup.swift 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174
  1. import CoreData
  2. import Foundation
  3. /// Represents statistical data about meal macronutrients for a specific day
  4. struct MealStats: Identifiable {
  5. let id = UUID()
  6. /// The date representing this time period
  7. let date: Date
  8. /// Total carbohydrates in grams
  9. let carbs: Double
  10. /// Total fat in grams
  11. let fat: Double
  12. /// Total protein in grams
  13. let protein: Double
  14. }
  15. extension Stat.StateModel {
  16. /// Sets up meal statistics by fetching and processing meal data
  17. ///
  18. /// This function:
  19. /// 1. Fetches hourly and daily meal statistics asynchronously
  20. /// 2. Updates the state model with the fetched statistics on the main actor
  21. /// 3. Calculates and caches initial daily averages
  22. func setupMealStats() {
  23. Task {
  24. let (hourly, daily) = await fetchMealStats()
  25. await MainActor.run {
  26. self.hourlyMealStats = hourly
  27. self.dailyMealStats = daily
  28. }
  29. // Initially calculate and cache daily averages
  30. await calculateAndCacheDailyAverages()
  31. }
  32. }
  33. /// Fetches and processes meal statistics from Core Data
  34. /// - Returns: A tuple containing hourly and daily meal statistics arrays
  35. ///
  36. /// This function:
  37. /// 1. Fetches carbohydrate entries from Core Data
  38. /// 2. Groups entries by hour and day
  39. /// 3. Calculates total macronutrients for each time period
  40. /// 4. Returns the processed statistics as (hourly: [MealStats], daily: [MealStats])
  41. private func fetchMealStats() async -> (hourly: [MealStats], daily: [MealStats]) {
  42. // Fetch CarbEntryStored entries from Core Data
  43. let results = await CoreDataStack.shared.fetchEntitiesAsync(
  44. ofType: CarbEntryStored.self,
  45. onContext: mealTaskContext,
  46. predicate: NSPredicate.carbsForStats,
  47. key: "date",
  48. ascending: true,
  49. batchSize: 100
  50. )
  51. return await mealTaskContext.perform {
  52. // Safely unwrap the fetched results, return empty arrays if nil
  53. guard let fetchedResults = results as? [CarbEntryStored] else { return ([], []) }
  54. let calendar = Calendar.current
  55. // Group entries by hour for hourly statistics
  56. let now = Date()
  57. let twentyDaysAgo = Calendar.current.date(byAdding: .day, value: -10, to: now) ?? now
  58. let hourlyGrouped = Dictionary(grouping: fetchedResults.filter { entry in
  59. guard let date = entry.date else { return false }
  60. return date >= twentyDaysAgo && date <= now
  61. }) { entry in
  62. let components = calendar.dateComponents([.year, .month, .day, .hour], from: entry.date ?? Date())
  63. return calendar.date(from: components) ?? Date()
  64. }
  65. // Group entries by day for daily statistics
  66. let dailyGrouped = Dictionary(grouping: fetchedResults) { entry in
  67. calendar.startOfDay(for: entry.date ?? Date())
  68. }
  69. // Calculate statistics for each hour
  70. let hourlyStats = hourlyGrouped.keys.sorted().map { timePoint in
  71. let entries = hourlyGrouped[timePoint, default: []]
  72. return MealStats(
  73. date: timePoint,
  74. carbs: entries.reduce(0.0) { $0 + $1.carbs },
  75. fat: entries.reduce(0.0) { $0 + $1.fat },
  76. protein: entries.reduce(0.0) { $0 + $1.protein }
  77. )
  78. }
  79. // Calculate statistics for each day
  80. let dailyStats = dailyGrouped.keys.sorted().map { timePoint in
  81. let entries = dailyGrouped[timePoint, default: []]
  82. return MealStats(
  83. date: timePoint,
  84. carbs: entries.reduce(0.0) { $0 + $1.carbs },
  85. fat: entries.reduce(0.0) { $0 + $1.fat },
  86. protein: entries.reduce(0.0) { $0 + $1.protein }
  87. )
  88. }
  89. return (hourlyStats, dailyStats)
  90. }
  91. }
  92. /// Calculates and caches the daily averages of macronutrients
  93. ///
  94. /// This function:
  95. /// 1. Groups meal statistics by day
  96. /// 2. Calculates average carbs, fat and protein for each day
  97. /// 3. Caches the results for later use
  98. ///
  99. /// This only needs to be called once during subscribe.
  100. private func calculateAndCacheDailyAverages() async {
  101. let calendar = Calendar.current
  102. // Calculate averages in context
  103. let dailyAverages = await mealTaskContext.perform { [dailyMealStats] in
  104. // Group by days
  105. let groupedByDay = Dictionary(grouping: dailyMealStats) { stat in
  106. calendar.startOfDay(for: stat.date)
  107. }
  108. // Calculate averages for each day
  109. var averages: [Date: (Double, Double, Double)] = [:]
  110. for (day, stats) in groupedByDay {
  111. let total = stats.reduce((0.0, 0.0, 0.0)) { acc, stat in
  112. (acc.0 + stat.carbs, acc.1 + stat.fat, acc.2 + stat.protein)
  113. }
  114. let count = Double(stats.count)
  115. averages[day] = (total.0 / count, total.1 / count, total.2 / count)
  116. }
  117. return averages
  118. }
  119. // Update cache on main thread
  120. await MainActor.run {
  121. self.dailyAveragesCache = dailyAverages
  122. }
  123. }
  124. /// Returns the average macronutrient values for the given date range from the cache
  125. /// - Parameter range: A tuple containing the start and end dates to get averages for
  126. /// - Returns: A tuple containing the average carbs, fat and protein values for the date range
  127. func getCachedMealAverages(for range: (start: Date, end: Date)) -> (carbs: Double, fat: Double, protein: Double) {
  128. return calculateAveragesForDateRange(from: range.start, to: range.end)
  129. }
  130. /// Calculates the average macronutrient values for a given date range
  131. /// - Parameters:
  132. /// - startDate: The start date of the range to calculate averages for
  133. /// - endDate: The end date of the range to calculate averages for
  134. /// - Returns: A tuple containing the average carbs, fat and protein values for the date range
  135. func calculateAveragesForDateRange(from startDate: Date, to endDate: Date) -> (carbs: Double, fat: Double, protein: Double) {
  136. // Filter cached values to only include those within the date range
  137. let relevantStats = dailyAveragesCache.filter { date, _ in
  138. date >= startDate && date <= endDate
  139. }
  140. // Return zeros if no data exists for the range
  141. guard !relevantStats.isEmpty else { return (0, 0, 0) }
  142. // Calculate total macronutrients across all days
  143. let total = relevantStats.values.reduce((0.0, 0.0, 0.0)) { acc, avg in
  144. (acc.0 + avg.0, acc.1 + avg.1, acc.2 + avg.2)
  145. }
  146. // Calculate averages by dividing totals by number of days
  147. let count = Double(relevantStats.count)
  148. return (total.0 / count, total.1 / count, total.2 / count)
  149. }
  150. }