//
//  AudioManager.swift
//  Dialog_Demo
//
//  Created by songsong.sss on 2025/5/29.
//

// 定义一个协议用于音频处理回调
protocol AudioHandlerDelegate: AnyObject {
    func didReceiveRecordingData(_ buffer: UnsafeMutablePointer<UInt8>?, length: Int32)
    func didReceivePlayingingData(_ buffer: UnsafeMutablePointer<UInt8>?, length: Int32)
    func playerDidStart()
    func playerDidStop()
    
}

class AudioHandler: NSObject, ConvVoiceRecorderDelegate {
    
    weak var delegate: AudioHandlerDelegate?
    
    // MARK: - ConvVoiceRecorderDelegate 方法实现
    
    func recorderDidStart() {
        print("录音开始")
    }
    
    func recorderDidStop() {
        print("录音停止")
    }
    
    func voiceRecorded(_ buffer: UnsafeMutablePointer<UInt8>?, length len: Int32) {
        // 处理录音数据
        delegate?.didReceiveRecordingData(buffer, length: len)
    }
    
    func voiceDidFail(_ error: Error?) {
        print("录音失败: \(error?.localizedDescription ?? "未知错误")")
    }
    
    func playerDidStart() {
        print("播放开始")
        delegate?.playerDidStart()
    }
    
    func playerDrainDataFinish() {
        print("cached tts play finish")
        delegate?.playerDidStop()
    }
    
    func playerDidFinish() {
        print("播放完成")
    }
    
    func playSoundLevel(_ level: Int32) {
    }
    
    func playData(_ buffer: UnsafeMutablePointer<UInt8>?, length len: Int32) {
        // 处理播放数据回调
        delegate?.didReceivePlayingingData(buffer, length: len)
        
    }
}

class AudioManager {
    private let audioController = AudioController()
    private let audioHandler = AudioHandler()
    
    init() {
        // 设置代理
        audioController.delegate = audioHandler
    }
    
    // 添加方法来设置 AudioHandler 的代理
    func setAudioHandlerDelegate(_ delegate: AudioHandlerDelegate) {
        audioHandler.delegate = delegate
    }
    
    // MARK: - 录音相关方法
    
    func startRecording() {
        audioController.startRecorder()
    }
    
    func stopRecording(notify: Bool) {
        audioController.stopRecorder(notify)
    }
    
    func muteRecording() {
        audioController.mute()
    }
    
    func unmuteRecording() {
        audioController.unmute()
    }
    
    func isRecording() -> Bool {
        return audioController.isRecorderStarted()
    }
    
    // MARK: - 播放相关方法
    
    func startPlaying() {
        audioController.startPlayer()
    }
    
    func stopPlaying() {
        audioController.stopPlayer()
    }
    
    func writeAudioData(_ data: Data) -> Int {
        return data.withUnsafeBytes { bufferPointer -> Int in
            guard let baseAddress = bufferPointer.baseAddress else { return 0 }
            let pointer = baseAddress.assumingMemoryBound(to: Int8.self)
            return Int(audioController.write(pointer, length: Int32(data.count)))
        }
    }
    
    func setPlayerSampleRate(_ sampleRate: Int) {
        audioController.setPlayerSampleRate(Int32(sampleRate))
    }
    
    func isPlayerFinished() -> Bool {
        return audioController.checkPlayerFinish()
    }
    
    func cleanPlayerBuffer() {
        audioController.cleanPlayerBuffer()
    }
    
    /// 通知播放器写完所有数据
    func drainPlayer() {
        audioController.drain()
    }
    
    func isPlayerStopped() -> Bool {
        return audioController.isPlayerStopped()
    }
}
