my mind is shot. core data hasn't been my cup of tea.
print("saveTrigger called with trigger: \(trigger)")
let encoder = JSONEncoder()
let fm = FileManager.default
let documentsDirectory = fm.urls(for: .documentDirectory, in: .userDomainMask).first!
let reflectionsURL = documentsDirectory.appendingPathComponent("reflections.json")
let triggersDirectory = documentsDirectory.appendingPathComponent("Triggers")
// Create a new reflections file if it doesn't exist
if !fm.fileExists(atPath: reflectionsURL.path) {
let emptyData = Data()
fm.createFile(atPath: reflectionsURL.path, contents: emptyData, attributes: nil)
}
// Write the trigger to the reflections file
do {
let data = try encoder.encode(trigger)
try data.write(to: reflectionsURL)
print("Trigger saved to device: \(trigger)")
print("Reflections file URL: \(reflectionsURL)")
} catch {
print("Failed to save trigger: \(error)")
}
// Find the trigger file with the UUID inside the file
let triggerFileURL = triggersDirectory.appendingPathComponent("\(trigger.id).json")
if fm.fileExists(atPath: triggerFileURL.path) {
do {
let data = try Data(contentsOf: triggerFileURL)
let uuid = try JSONDecoder().decode(UUID.self, from: data)
let uuidString = uuid.uuidString
let matchingTriggerFileURL = triggersDirectory.appendingPathComponent("\(uuidString).json")
if fm.fileExists(atPath: matchingTriggerFileURL.path) {
try fm.removeItem(at: matchingTriggerFileURL)
print("Trigger file deleted: \(matchingTriggerFileURL.lastPathComponent)")
} else {
print("Trigger file not found")
}
} catch {
print("Error deleting trigger file: \(error.localizedDescription)")
}
} else {
print("Trigger file not found")
}
}