//
//  ListOfThingsView.swift
//  JustOneThing
//
//  Created by Alan Francis on 10/07/2023.
//

import SwiftUI
import CoreData

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

    @FetchRequest(
        sortDescriptors: [NSSortDescriptor(keyPath: \PersistentThing.createdAt, ascending: true)],
        animation: .default)
    private var things: FetchedResults<PersistentThing>
    private let timeFormatter: DateFormatter = {
        let formatter = DateFormatter()
        formatter.dateStyle = .none
        formatter.timeStyle = .medium
        return formatter
    }()

    var body: some View {
        NavigationView {
            List {
                ForEach(things) { thing in
                    NavigationLink {
                        Text(thing.text ?? "no text")
                    } label: {
                        Text(thing.text ?? "no text")
                    }
                }
                .onDelete(perform: deleteItems)
            }
            #if os(iOS)
                .toolbar {
                    ToolbarItem(placement: .navigationBarTrailing) {
                        EditButton()
                    }
                    ToolbarItem {
                        Button(action: addItem) {
                            Label("Add Item", systemImage: "plus")
                        }
                    }
                }
            #endif
            Text("Select an item")
        }
    }

    private func addItem() {
        withAnimation {
            let newThing = PersistentThing(context: viewContext)
            newThing.createdAt = Date()
            newThing.uuid = UUID()
            newThing.text = "thing created \(timeFormatter.string(from: Date()))"

            do {
                try viewContext.save()
            } catch {
                // Replace this implementation with code to handle the error appropriately.
                // fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
                let nsError = error as NSError
                fatalError("Unresolved error \(nsError), \(nsError.userInfo)")
            }
        }
    }

    private func deleteItems(offsets: IndexSet) {
        withAnimation {
            offsets.map { things[$0] }.forEach(viewContext.delete)

            do {
                try viewContext.save()
            } catch {
                // Replace this implementation with code to handle the error appropriately.
                // fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
                let nsError = error as NSError
                fatalError("Unresolved error \(nsError), \(nsError.userInfo)")
            }
        }
    }
}
