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

import SwiftUI

struct ActivitiesView: View {
    
    @Environment(\.managedObjectContext) private var viewContext

    @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 {
        
        VStack {
            if self.records.isEmpty {
                Text("You don't have any recorded activity yet")
            } else {
                
                List {
                    ForEach(self.activities) { activity in
                        NavigationLink {
                            ActivityView(activity: activity)
                                .environment(\.managedObjectContext, viewContext)
                        } label: {
                            HStack {
                                Text(activity.name ?? "no activity")
                                Spacer()
                                Text(activity.recordCount)
                                    .font(.system(.body, weight: .bold))
                                    .foregroundColor(.accentColor)
                            }
                        }
                    }
                }
            }
        }
        .navigationTitle("Activities")
        
    }
}

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