//
//  PersistenceDELETE.swift
//  Feels
//
//  Created by Trey Tartt on 2/17/22.
//

import CoreData

extension PersistenceController {
    func clearDB() {
        let fetchRequest: NSFetchRequest<NSFetchRequestResult> = NSFetchRequest(entityName: "MoodEntry")
        let deleteRequest = NSBatchDeleteRequest(fetchRequest: fetchRequest)
        
        do {
            try viewContext.executeAndMergeChanges(using: deleteRequest)
            saveAndRunDataListerners()
        } catch let error as NSError {
            fatalError("Unresolved error \(error), \(error.userInfo)")
        }
    }
    
    func deleteLast(numberOfEntries: Int) {
        let entries = PersistenceController.shared.getData(startDate: Calendar.current.date(byAdding: .day, value: -numberOfEntries, to: Date())!,
                                                           endDate: Date(),
                                                           includedDays: [])
        for entry in entries {
            viewContext.delete(entry)
        }
        try! viewContext.save()
    }
}
