//
//  TextToSpeechRecorder.swift
//  LeCountdown
//
//  Created by Laurent Morvillier on 07/02/2023.
//

import Foundation
import AVFoundation

struct TextToSpeechFile: Codable {
    var speech: String
    var fileName: String
}

class TextToSpeechRecorder {
    
    static func record(speech: String, handler: @escaping (Result<TextToSpeechFile, Error>) -> Void) {
        let synthesizer = AVSpeechSynthesizer()
        let utterance = AVSpeechUtterance(string: speech)
        utterance.voice = AVSpeechSynthesisVoice(language: "fr-FR")

        synthesizer.speak(utterance)
        return
        
        var output: AVAudioFile?
        
        synthesizer.write(utterance) { buffer in
            guard let pcmBuffer = buffer as? AVAudioPCMBuffer else {
                fatalError("unknown buffer type: \(buffer)")
            }
            let fileName = "\(UUID().uuidString).caf"
            if pcmBuffer.frameLength == 0 {
                handler(.success(TextToSpeechFile(speech: speech, fileName: fileName)))
                // done
            } else {
                // append buffer to file
                do {
                    if output == nil {
                        
                        output = try AVAudioFile(
                            forWriting: URL(fileURLWithPath: fileName),
                            settings: pcmBuffer.format.settings,
                            commonFormat: .pcmFormatInt16,
                            interleaved: false)
                    }
                    try output?.write(from: pcmBuffer)
                } catch {
                    Logger.error(error)
                    handler(.failure(error))
                }
            }
        }
    }
    
}
