//
//  CoreDataRequests.swift
//  LeCountdown
//
//  Created by Laurent Morvillier on 26/01/2023.
//

import Foundation
import CoreData

enum CountdownException : Error {
    case entityNameNotFound
}

class CoreDataRequests {
    
    static func findBy<T : NSManagedObject, V>(property: String, value: V) throws -> T? {
        
        let context = PersistenceController.shared.container.viewContext
        if let entityName = T.entity().name {
            let fetchRequest = NSFetchRequest<T>(entityName: entityName)
            fetchRequest.predicate = NSPredicate(format: "%K == %@", argumentArray: [property, value])
            let results = try context.fetch(fetchRequest)
            return results.first
        } else {
            throw CountdownException.entityNameNotFound
        }
        
    }
    
    static func getOrCreateActivity(name: String) -> Activity {
        do {
            if let activity: Activity = try findBy(property: #keyPath(Activity.name), value: name) {
                return activity
            }
        } catch {
            Logger.error(error)
            print("error = \(error)")
        }
        let context = PersistenceController.shared.container.viewContext
        let activity = Activity(context: context)
        activity.name = name
        return activity
    }
    
    static func recordActivity(timer: AbstractTimer, dateInterval: DateInterval) throws {
        
        guard let activity = timer.activity else {
            return
        }
        
        let context = PersistenceController.shared.container.viewContext
        let record = Record(context: context)
        record.start = dateInterval.start
        record.end = dateInterval.end
        record.activity = activity
        
        try context.save()
    }
    
}
