//
//  CoreDataDelegete.swift
//  MusicPlayer
//
//  Created by Mr.Zhou on 2024/4/1.
//

import Foundation
import CoreData
// MARK: - CoreDataManageableDelegate 数据库管理协议
///数据库管理协议，继承NSFetchRequestResult，方便调用更多方法
protocol MP_CoreDataManageableDelegate: NSFetchRequestResult {
    ///实体名
    static var entityName: String { get }
}
///扩展数据库管理协议，继承NSManagedObject时，默认实现以下内容
extension MP_CoreDataManageableDelegate where Self: NSManagedObject {
    //根据类名设置实体名
    static var entityName: String {
        return String(describing: self)
    }
    //标准检索
    static var fetchRequest: NSFetchRequest<Self> {
        return NSFetchRequest<Self>(entityName: entityName)
    }
}
// MARK: - CoreDataOperationDelegate 数据库操作协议
///数据库操作协议，创建，查询，删除，保存等
protocol MP_CoreDataOperationDelegate {
    //关联一个继承CoreDataManageableDelegate协议的实体，与泛型相似
    associatedtype ManagedObject: MP_CoreDataManageableDelegate, NSManagedObject
    //创建实体
    static func create() -> ManagedObject
    //查询指定条件实体
    static func fetch(_ predicate:NSPredicate) -> [ManagedObject]
    //查询全部实体
    static func fetchAll() -> [ManagedObject]
    //删除实体
    static func delete(_ object: ManagedObject)
    //表保存
    static func save()
}
///扩展数据库操作协议，默认实现协议方法
extension MP_CoreDataOperationDelegate {
    
    /// 创建实体
    /// - Returns: 返回的实体
    static func create() -> ManagedObject {
        //创建一个对应的实体
        guard let entity = NSEntityDescription.entity(forEntityName: ManagedObject.entityName, in: MP_CoreDataHandlerManager.shared.context) else {
            fatalError("Failed to find entity description for \(ManagedObject.entityName)")
        }
        return ManagedObject(entity: entity, insertInto: MP_CoreDataHandlerManager.shared.context)
    }
    
    /// 查询指定条件实体
    /// - Parameter predicate: 条件语句
    /// - Returns: 返回结果数组
    static func fetch(_ predicate:NSPredicate) -> [ManagedObject] {
        let fetchRequest = ManagedObject.fetchRequest
        fetchRequest.predicate = predicate
        do {
            return try MP_CoreDataHandlerManager.shared.context.fetch(fetchRequest)
        } catch {
            print("Failed to fetch \(ManagedObject.entityName): \(error)")
            return []
        }
    }
    
    /// 查询全部实体
    /// - Returns: 返回结果数组
    static func fetchAll() -> [ManagedObject] {
        do {
            return try MP_CoreDataHandlerManager.shared.context.fetch(ManagedObject.fetchRequest)
        } catch {
            print("Failed to fetch \(ManagedObject.entityName): \(error)")
            return []
        }
    }
    /// 从表删除实体
    /// - Parameter object: 指定的实体
    static func delete(_ object: ManagedObject) {
        MP_CoreDataHandlerManager.shared.context.delete(object)
        save()
    }
    
    /// 表执行保存
    static func save() {
        MP_CoreDataHandlerManager.shared.saveContext()
    }
}
