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

import SwiftUI

struct ActivitiesView: 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 {
        
        VStack {
            if self.records.isEmpty {
                Text("You don't have any recorded activity yet")
            } else {
                List {
                    ForEach(self.activities) { activity in
                        NavigationLink {
                            HStack {
                                StatsView(activity: activity).frame(width: 300)
                                    .background(.red)
                                RecordsView(activity: activity)
                                    .frame(maxWidth: .infinity)
                                    .background(.green)
                            }
                            
                        } label: {
                            HStack {
                                Text(activity.name ?? "no activity")
                                Spacer()
                                Text(activity.recordCount)
                            }
                        }
                    }
                }
            }
        }
        .navigationTitle("Activities")
        
    }
}

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