//
//  BFCoreDataModel.swift
//  BFFramework
//
//  Created by 胡志强 on 2021/11/12.
//

import CoreData
import Foundation

let persistentContext = BFDataPersistentManager.shared.persistentContainer.viewContext
open class BFCoreDataModel: NSObject, NSFetchRequestResult {
    public class func createModel(modelName: String) -> AnyObject {
        return NSEntityDescription.insertNewObject(forEntityName: modelName, into: persistentContext)
    }

    public func save() {
        do {
            try persistentContext.save()
        } catch {
            fatalError("不能保存：\(error)")
        }
    }

    public class func getList(fetchRequest: NSFetchRequest<NSFetchRequestResult>) -> [NSFetchRequestResult]? {
        do {
            let fetchedObjects = try persistentContext.fetch(fetchRequest)
            return fetchedObjects as? [NSFetchRequestResult]
        } catch {
            fatalError("不能保存：\(error)")
        }
    }

    public func deleteMode(fetchRequest: NSFetchRequest<NSFetchRequestResult>) {
        do {
            let fetchedObjects = try persistentContext.fetch(fetchRequest)
            for info in fetchedObjects {
                persistentContext.delete(info as! NSManagedObject)
            }
            try! persistentContext.save()
        } catch {
            fatalError("不能保存：\(error)")
        }
    }
}
