import SwiftUI
import Observation
import AVFoundation

@Observable class ApplicationData {
   let synthesizer: AVSpeechSynthesizer
   let listVoices: [AVSpeechSynthesisVoice]
   var selectedVoice: String = ""

   static let shared: ApplicationData = ApplicationData()
   private init() {
      synthesizer = AVSpeechSynthesizer()

      // Get voices for current locale
      let userLanguage = AVSpeechSynthesisVoice.currentLanguageCode()
      let list = AVSpeechSynthesisVoice.speechVoices()
      listVoices = list.filter { voice in
         return voice.language == userLanguage
      }
      if let first = listVoices.first {
         selectedVoice = first.identifier
      }
   }
   func say(text: String) {
      let utterance = AVSpeechUtterance(string: text)
      utterance.voice = AVSpeechSynthesisVoice(identifier: selectedVoice)
      synthesizer.speak(utterance)
   }
}