//
/* NOTICE: All information contained herein is, and remains the property of Brightinsight Inc. or its customer. 
The intellectual and technical concepts contained herein are proprietary to Brightinsight Inc. or its customer and may be covered by U.S. and Foreign Patents, patents in process, and are protected by trade secret or copyright law.
Dissemination of this information or reproduction of this material is strictly forbidden unless prior written permission is obtained from Brightinsight Inc. or its customer. Access to the source code contained herein is hereby forbidden to anyone except current Brightinsight Inc. employees, managers or contractors who have executed
Confidentiality and Non-disclosure agreements explicitly covering such access.
*/
/**
* System Name : BISDKCore
* Component ID : BISDKDatabase
* Description : 
* Author: Arnold Dominguez
* Copyright © : Brightinsight, Inc.
* -----------------------
* Revision Change
* -----------------------
* Author                        Date             Version            Change-Description
 Arnold Dominguez       08/10/21            1.0                 Creation
 Arnold Dominguez       09/15/21            1.1                 Documentation
*========================================================================================================
*/

import Foundation
import CoreData

/// Represents a local database, directly interacting with `CoreData`.
class BISDKDatabase {
    private var identifier: String
    
    init(identifier: String) {
        self.identifier = identifier
    }
    
    private lazy var persistentContainer: NSPersistentContainer = initializePersistentContainer()
    
    lazy var context: NSManagedObjectContext = persistentContainer.viewContext
    
    func saveContext() {
        guard context.hasChanges else { return }
        
        do {
            try context.save()
        } catch let nserror as NSError {
            print("Could not save context: \(nserror), \(nserror.userInfo)")
        }
    }
}
private extension BISDKDatabase {
    func initializePersistentContainer() -> NSPersistentContainer {
        #if DEBUG
        let bundle = Bundle(for: BISDKDatabase.self)
                
        guard
            let modelURL = bundle.url(forResource: identifier, withExtension: "momd"),
            let objectModel = NSManagedObjectModel(contentsOf: modelURL)
        else { fatalError("Could not get URL for model named \(identifier)") }
        
        let container = NSPersistentContainer(name: identifier, managedObjectModel: objectModel)
        #else
        let container = NSPersistentContainer(name: identifier)
        #endif
        container.loadPersistentStores(completionHandler: { (storeDescription, error) in
            guard let error = error as NSError? else { return }
            fatalError("Could no load persistent stores: \(error.userInfo)")
        })
        
        return container
    }
}
