//
//  CDManager.swift
//  Zockerhoehle
//
//  Created by Julian-Steffen Müller on 24.06.19.
//  Copyright © 2019 Julian-Steffen Müller. All rights reserved.
//

import Foundation
import CoreData

class CDManager {
    
    static let shared : CDManager = CDManager();
    
    static var preview: CDManager = {
        let controller = CDManager(inMemory: true)

        //INIT Core Data

        return controller
    }()
    
    let persistentContainer : NSPersistentCloudKitContainer
    
    private init(inMemory: Bool = false) {
            // If you didn't name your model Main you'll need
            // to change this name below.
        persistentContainer = NSPersistentCloudKitContainer(name: "Zockerhoehle")

        if inMemory {
            persistentContainer.persistentStoreDescriptions.first?.url = URL(fileURLWithPath: "/dev/null")
        }

        persistentContainer.loadPersistentStores { description, error in
                if let error = error {
                    fatalError("Error: \(error.localizedDescription)")
                }
            }
    }
    
    // MARK: - Core Data stack
    
//    lazy var persistentContainer: NSPersistentContainer = {
//        /*
//         The persistent container for the application. This implementation
//         creates and returns a container, having loaded the store for the
//         application to it. This property is optional since there are legitimate
//         error conditions that could cause the creation of the store to fail.
//         */
//        let container = NSPersistentCloudKitContainer(name: "Zockerhoehle")
//
//        container.loadPersistentStores(completionHandler: { (storeDescription, error) in
//            if let error = error as NSError? {
//                // 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.
//
//                /*
//                 Typical reasons for an error here include:
//                 * The parent directory does not exist, cannot be created, or disallows writing.
//                 * The persistent store is not accessible, due to permissions or data protection when the device is locked.
//                 * The device is out of space.
//                 * The store could not be migrated to the current model version.
//                 Check the error message to determine what the actual problem was.
//                 */
//                fatalError("Unresolved error \(error), \(error.userInfo)")
//            }
//        })
//        container.viewContext.automaticallyMergesChangesFromParent = true
//        return container
//    }()
//
//    lazy var persistentContainerPreview: NSPersistentContainer = {
//        /*
//         The persistent container for the application. This implementation
//         creates and returns a container, having loaded the store for the
//         application to it. This property is optional since there are legitimate
//         error conditions that could cause the creation of the store to fail.
//         */
//        let container = NSPersistentContainer(name: "Zockerhoehle")
//
//        container.loadPersistentStores(completionHandler: { (storeDescription, error) in
//            if let error = error as NSError? {
//                // 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.
//
//                /*
//                 Typical reasons for an error here include:
//                 * The parent directory does not exist, cannot be created, or disallows writing.
//                 * The persistent store is not accessible, due to permissions or data protection when the device is locked.
//                 * The device is out of space.
//                 * The store could not be migrated to the current model version.
//                 Check the error message to determine what the actual problem was.
//                 */
//                fatalError("Unresolved error \(error), \(error.userInfo)")
//            }
//        })
//
//        container.viewContext.automaticallyMergesChangesFromParent = true
//        return container
//    }()
    
    lazy var viewContext : NSManagedObjectContext = {
        self.persistentContainer.viewContext
    }()
    
    lazy var viewContextPreview : NSManagedObjectContext = {
        self.persistentContainer.viewContext
    }()
    // MARK: - Core Data Saving support
    
    func saveContext () {
        print("CHANGES: \(self.persistentContainer.viewContext.hasChanges)")
        self.persistentContainer.performBackgroundTask({(context) in
            print("Context \(context.hasChanges)")
            if context.hasChanges {
                do {
                    try context.save()
                    print("--------------------saved-------")
                } 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)")
                }
            }
        })
    }
}
