import SwiftUI

class ApplicationData {
   let manager: FileManager
   let directories: [URL]?

   static let shared: ApplicationData = ApplicationData()
   private init() {
      manager = FileManager.default
      directories = manager.urls(for: .documentDirectory, in: .userDomainMask)
   }
   func openFile() -> NSAttributedString {
      var text = NSAttributedString(string: "")

      guard let docURL = directories?.first else { return text }
      let fileURL = docURL.appendingPathComponent("myFile.rtfd")
      do {
         if manager.fileExists(atPath: fileURL.path) {
            // Read file and convert data into NSAttributedString
            if let content = manager.contents(atPath: fileURL.path) {
               let ns = try NSAttributedString(data: content, documentAttributes: nil)
               text = ns
            }
         }
      } catch {
         print("Error loading file: \(error)")
      }
      return text
   }
   func saveFile(text: NSAttributedString) {
      guard let docURL = directories?.first else { return }
      let fileURL = docURL.appendingPathComponent("myFile.rtfd", isDirectory: true)
      do {
         // Convert NSAttributedString into data and save it
         let data = try text.data(from: NSRange(location: 0, length: text.length), documentAttributes: [.documentType: NSAttributedString.DocumentType.rtfd])
         try data.write(to: fileURL)
      } catch {
         print("Error saving file: \(error)")
      }
   }
}