import CoreData
import Foundation

struct PersistenceController {
    static let shared = PersistenceController()

    static var preview: PersistenceController = {
        let result = PersistenceController(inMemory: true)
        let viewContext = result.container.viewContext

        // Create sample data for previews
        let sampleLink = Link(context: viewContext)
        sampleLink.alias = "example"
        sampleLink.originalURL = "https://example.com"
        sampleLink.linkType = "LINK"
        sampleLink.clickCount = 5
        sampleLink.createdAt = Date()
        sampleLink.updatedAt = Date()
        sampleLink.linkDescription = "An example link"

        let sampleTag = Tag(context: viewContext)
        sampleTag.name = "Sample"
        sampleTag.slug = "sample"
        sampleTag.createdAt = Date()

        sampleLink.addToTags(sampleTag)

        do {
            try viewContext.save()
        } catch {
            let nsError = error as NSError
            fatalError("Unresolved error \(nsError), \(nsError.userInfo)")
        }
        return result
    }()

    let container: NSPersistentContainer

    init(inMemory: Bool = false) {
        container = NSPersistentContainer(name: "CoreDataModel")
        if inMemory {
            container.persistentStoreDescriptions.first!.url = URL(fileURLWithPath: "/dev/null")
        }

        container.loadPersistentStores(completionHandler: { (storeDescription, error) in
            if let error = error as NSError? {
                fatalError("Unresolved error \(error), \(error.userInfo)")
            }
        })

        container.viewContext.automaticallyMergesChangesFromParent = true
    }
}

// MARK: - Save context
extension PersistenceController {
    func save() {
        let context = container.viewContext

        if context.hasChanges {
            do {
                try context.save()
            } catch {
                let nsError = error as NSError
                fatalError("Unresolved error \(nsError), \(nsError.userInfo)")
            }
        }
    }
}
