//
//  RecordsView.swift
//  LeCountdown
//
//  Created by Laurent Morvillier on 26/01/2023.
//

import SwiftUI

struct RecordsView: View {
    
    @FetchRequest(
        sortDescriptors: [NSSortDescriptor(keyPath: \Record.start, ascending: false)],
        animation: .default)
    private var records: FetchedResults<Record>
    
    @FetchRequest(
        sortDescriptors: [NSSortDescriptor(keyPath: \Activity.name, ascending: true)],
        predicate: NSPredicate(format: "records.@count > 0"), animation: .default)
    private var activities: FetchedResults<Activity>
    
    var body: some View {
        
        Group {
            if records.isEmpty {
                Text("You don't have any recorded activity yet")
            } else {
                List {
                    ForEach(activities) { activity in
                        HStack {
                            Text(activity.name ?? "no activity")
                            Spacer()
                            Text(activity.recordCount)
                        }
                    }
                }
            }
        }.navigationTitle("Activities")
        
    }
}

struct RecordsView_Previews: PreviewProvider {
    static var previews: some View {
        NavigationStack {
            RecordsView().environment(\.managedObjectContext, PersistenceController.preview.container.viewContext)
        }
    }
}
