50 lines
1.1 KiB
Swift
50 lines
1.1 KiB
Swift
import Foundation
|
|
|
|
@MainActor @Observable
|
|
final class HomeViewModel {
|
|
var todayEntries: [FoodEntry] = []
|
|
var goal: DailyGoal = .defaultGoal
|
|
var isLoading = true
|
|
var errorMessage: String?
|
|
|
|
private let repo = FitnessRepository.shared
|
|
|
|
var totalCalories: Double {
|
|
todayEntries.reduce(0) { $0 + $1.calories }
|
|
}
|
|
|
|
var totalProtein: Double {
|
|
todayEntries.reduce(0) { $0 + $1.protein }
|
|
}
|
|
|
|
var totalCarbs: Double {
|
|
todayEntries.reduce(0) { $0 + $1.carbs }
|
|
}
|
|
|
|
var totalFat: Double {
|
|
todayEntries.reduce(0) { $0 + $1.fat }
|
|
}
|
|
|
|
var entryCount: Int {
|
|
todayEntries.count
|
|
}
|
|
|
|
func load() async {
|
|
isLoading = true
|
|
errorMessage = nil
|
|
let today = Date().apiDateString
|
|
|
|
do {
|
|
async let entriesTask = repo.entries(for: today, forceRefresh: true)
|
|
async let goalsTask = repo.goals(for: today)
|
|
|
|
todayEntries = try await entriesTask
|
|
goal = try await goalsTask
|
|
} catch {
|
|
errorMessage = error.localizedDescription
|
|
}
|
|
|
|
isLoading = false
|
|
}
|
|
}
|