//
//  RecordsView.swift
//  LeCountdown
//
//  Created by Laurent Morvillier on 17/02/2023.
//

import SwiftUI
import CoreData

class RecordsModel: ObservableObject {

    @Published var filters: [Filter] = []

    func loadFilters(activity: Activity, timeFrame: TimeFrame, context: NSManagedObjectContext) {
        self.filters = timeFrame.filters(context: context, activity: activity)
    }

}

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

    let activity: Activity
    let filters: [Filter]
    
    var body: some View {
        ForEach(self.filters) { filter in
            RecordsSectionView(activity: self.activity, filter: filter)
                .environment(\.managedObjectContext, viewContext)
        }
    }
    
}

class RecordsSectionModel: ObservableObject {
    
    @Published var records: [Record] = []
    
    func loadRecords(activity: Activity, filter: Filter, context: NSManagedObjectContext) {
        let records = self._retrieveRecords(activity: activity, filter: filter, context: context)
        self.records = records
    }
    
    fileprivate func _retrieveRecords(activity: Activity, filter: Filter, context: NSManagedObjectContext) -> [Record] {
        do {
            let request = Record.fetchRequest()
            let activityPredicate = NSPredicate(format: "activity = %@", activity)
            request.predicate = NSCompoundPredicate(andPredicateWithSubpredicates: [activityPredicate, filter.predicate])
            request.sortDescriptors = [NSSortDescriptor(key: "start", ascending: false)]
            return try context.fetch(request)
        } catch {
            Logger.log(error)
            return []
        }
    }
    
    func deleteItem(_ indexSet: IndexSet, context: NSManagedObjectContext) {
        
        for index in indexSet {
            let item = self.records[index]
            context.delete(item)
            
            do {
                try context.save()
            } catch {
                Logger.error(error)
            }
        }

    }
    
}

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

    var activity: Activity
    @State var filter: Filter
    
    @StateObject var model: RecordsSectionModel = RecordsSectionModel()
    
    var body: some View {
        
        Section(filter.localizedString) {
            ForEach(self.model.records) { record in
                HStack {
                    Text(record.formattedDay)
                    Spacer()
                    if let duration = record.duration {
                        Text(duration.minuteSecond)
                    }
                }
            }.onDelete(perform: _deleteItem)
        }.onAppear {
            self.model.loadRecords(activity: self.activity,
                                   filter: self.filter,
                                   context: viewContext)
        }
        
    }
    
    fileprivate func _deleteItem(_ indexSet: IndexSet) {
        self.model.deleteItem(indexSet, context: self.viewContext)
    }
    
}

struct RecordsView_Previews: PreviewProvider {
    static var previews: some View {
        RecordsView(activity:
                        Activity.fake(context: PersistenceController.preview.container.viewContext),
                    filters: [Filter.none])
        .environment(\.managedObjectContext, PersistenceController.preview.container.viewContext)
    }
}
