//
//  TSAudioPlayer+Ex.swift
//  AIRingtone
//
//  Created by 100Years on 2025/3/18.
//

class TSAudioPlayerFileTool {
    
    
    var downloadOp:DownloadOperation?
    var urlString:String
    init(urlString:String) {
        self.urlString = urlString

    }
    
    
    func playAudio(urlString:String){
        guard let url = URL(string: urlString) else { return }
        
        // 检查本地是否已存在文件
        if let localFilePath = DownloadManager.localFilePath(for: url) {
            print("File already exists at: \(localFilePath)")
            kAudioAVPlayerShared.loadAudio(from: localFilePath)
            kAudioAVPlayerShared.play()
        } else {
            // 开始下载任务
            downloadOp = DownloadManager.shared.downloadFile(from: url)

            // 设置进度回调
            downloadOp?.progressHandler = { progress in
                print("Download progress: \(progress)")
                
                kAudioAVPlayerShared.onPlaybackStateChanged?(.loading(progress))
            }

            // 设置完成回调
            downloadOp?.completionHandler = { tempURL, error in
                if let tempURL = tempURL {
                    print("Download completed, file saved at: \(tempURL)")
                    kAudioAVPlayerShared.loadAudio(from: tempURL)
                    kAudioAVPlayerShared.play()
                    
                } else if let error = error {
                    print("Download failed: \(error)")
                }
            }

            // 开始下载
            downloadOp?.startDownload()
        }
    }
    
    func stopAudio(urlString:String){
        
        if let downloadOp = downloadOp {
            // 暂停下载
            downloadOp.pause()
            kAudioAVPlayerShared.stop()
        }
    }
}
