//
//  NSManagedContext+Extensions.swift
//  LeCountdown
//
//  Created by Laurent Morvillier on 24/01/2023.
//

import Foundation
import CoreData

extension NSManagedObjectContext {
    
    func object(stringId: String) -> NSManagedObject? {
        guard let url = URL(string: stringId) else { return nil }
        guard let objectId = PersistenceController.shared.container.persistentStoreCoordinator.managedObjectID(forURIRepresentation: url) else { return nil }
        return self.object(with: objectId)
    }
    
    func distinct(entityName: String, attributes: [String], predicate: NSPredicate? = nil) throws -> [Any] {

        let request = NSFetchRequest<NSFetchRequestResult>(entityName: entityName)
        
        request.entity = NSEntityDescription.entity(forEntityName: entityName, in: self)
        request.returnsDistinctResults = true
        request.resultType = .dictionaryResultType
        request.predicate = predicate
        if let entity = request.entity {
            let entityProperties = entity.propertiesByName
            var properties = [NSPropertyDescription]()
            for attribute in attributes {
                if let entityDescription = entityProperties[attribute] {
                    properties.append(entityDescription)
                }
            }
            request.propertiesToFetch = properties
        }
        
        return try self.fetch(request)
    }
    
    func count(entityName: String) throws -> Int {
        let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: entityName)
        return try self.count(for: fetchRequest)
    }
    
}

extension NSManagedObject {
    
    var isTemporary: Bool {
        return self.objectID.isTemporaryID
    }
    
    var stringId: String {
        return self.objectID.uriRepresentation().absoluteString
    }
    
}
