//
//  TSBusinessAudioPlayer.swift
//  AIRingtone
//
//  Created by 100Years on 2025/3/7.
//


class TSBusinessAudioPlayer {
    
    static let shared = TSBusinessAudioPlayer()
    
    enum PlayerState:Equatable {
        case play
        case pause
        case stop
        case loading(Float)
        case volume(Float)
        case currentTime(Double)
    }
    
    private var audioPlayer: TSAudioPlayer?
    
    var stateChangedHandle:((PlayerState) -> Void)?
    var currentPlayerState:PlayerState = .stop
    var duration:Double{
        if let audioPlayer = audioPlayer {
            return audioPlayer.duration
        }
        return 0.0
    }

    var isPlaying:Bool{
        if let audioPlayer = audioPlayer {
            return audioPlayer.isPlaying
        }
        return false
    }
    
    var isLoading:Bool{
        switch currentPlayerState {
        case .loading(let float):
            return float < 1.0 ? true : false
        default:
            return false
        }
    }
    
    var currentTime:Double{
        if let audioPlayer = audioPlayer {
            return audioPlayer.currentTime
        }
        return 0.0
    }
    
    
    var playProgress:Double{
        let playProgress = currentTime / duration
        dePrint("TSAudioPlayer playProgress = \(playProgress)")
        return playProgress
    }
    
    //播放器是否可用
    var playerUsable:Bool {
        if let audioPlayer = audioPlayer {
            return audioPlayer.playerUsable
        }
        return false
    }
    var currentURLString:String = ""
    var currentIndexPath:IndexPath? = nil
    
    //加载音乐可能 2-3 秒有结果,停止加载后播放.
    private var isStopPlayingAfterLoading:Bool = false

    func isPlayURLString(string:String,indexPath:IndexPath? = nil) -> Bool {

        if currentURLString == string {
            if let currentIndexPath = currentIndexPath,
               let indexPath = indexPath,
               indexPath != currentIndexPath
            {
                return false
            }else{
                return true
            }
        }
        return false
    }
    

    func playUrlString(_ urlString:String?,loop:Bool = false,indexPath:IndexPath? = nil) {
        self.stop()
        if let urlString = urlString {
            
//            if self.currentURLString == urlStrin {
//                self.play()
//                return
//            }
            self.currentURLString = urlString
            self.currentIndexPath = indexPath

            let palyFile:(URL)->Void = { [weak self] url in
                guard let self = self else { return }
                debugPrint("TSAudioPlayer 正在播放url:\(currentURLString)")
                debugPrint("TSAudioPlayer 正在播放path:\(url)")
                self.audioPlayer = TSAudioPlayer(url: url)
                self.audioPlayer?.setLoop(loop)
                
                if self.audioPlayer?.volume == 0 {
                    setVolume(volume: 1.0)
                }
                
                self.audioPlayer?.currentTimeChanged = { [weak self] currentTime in
                    guard let self = self else { return }
                    changePlayerState(.currentTime(currentTime))
                }
                
                self.play()
                dePrint(self.audioPlayer?.duration)
                
                self.audioPlayer?.audioPlayerDidFinishHandle = { [weak self] flag in
                    guard let self = self else { return }
                    if flag == true, self.audioPlayer?.isLooping == false{
                        stop()
                    }
                }
            }
            
            isStopPlayingAfterLoading = false
            if let path = TSCommonTool.getCachedURLString(from: urlString,missingEx: "mp3") {
                palyFile(path) //播放
            }else{
                self.changePlayerState(.loading(0.0))
                TSCommonTool.downloadAndCacheFile(from: urlString,missingEx: "mp3") { [weak self] path, error in
                    guard let self = self else { return }
                    self.changePlayerState(.loading(1.0))
                
                    if isStopPlayingAfterLoading == true || currentURLString != urlString{
                        isStopPlayingAfterLoading = false
                        return
                    }
                    
                    if let path = path {
                        palyFile(URL(fileURLWithPath: path)) //播放
                    }else{
                        //暂停
                        self.stop()
                    }
                }
            }
        }
    }
    

    func play() {
        self.audioPlayer?.play()
        changePlayerState(.play)
    }
    
    func stop() {
        isStopPlayingAfterLoading = true
        currentURLString = ""
        self.audioPlayer?.stop()
        changePlayerState(.stop)
    }
    
    func pause() {
        isStopPlayingAfterLoading = true
        self.audioPlayer?.pause()
        changePlayerState(.pause)
    }
    
    func setVolume(volume:Float){
        self.audioPlayer?.volume = volume 
//        self.audioPlayer?.setVolume(volume)
        changePlayerState(.volume(volume))
    }
    

    func changeAudioSwitch()->Float {
        let volume:Float = self.audioPlayer?.volume == 0.0 ? 1.0 : 0.0
        setVolume(volume: volume)
        return volume
    }
    
    func changePlayerState(_ state:PlayerState){
        debugPrint("TSAudioPlayer changePlayerState=\(state)")
        currentPlayerState = state
        
        kExecuteOnMainThread{
            self.stateChangedHandle?(state)
            NotificationCenter.default.post(name: .kBusinessAudioStateChange, object: nil, userInfo: ["PlayerState": state])
        }
    }
     
    deinit {
        dePrint("TSAudioPlayer TSBusinessAudioPlayer deinit")
    }
}
