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


class TSBusinessAudioPlayer {
    
    static let shared = TSBusinessAudioPlayer { state in
        kExecuteOnMainThread{
            NotificationCenter.default.post(name: .kBusinessAudioStateChange, object: nil, userInfo: ["PlayerState": state])
        }
    }
    
    enum PlayerState:Equatable {
        case play
        case pause
        case stop
        case loading(Float)
        case volume(Float)
    }
    
    private var audioPlayer: TSAudioPlayer?
    
    var stateChangeBlock:(PlayerState) -> Void
    
    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 isStop:Bool = false
    
    init(stateChangeBlock:@escaping (PlayerState) -> Void) {
        self.stateChangeBlock = stateChangeBlock
    }
    
    func playRingtone(ringtone:String?) {
        if let ringtone = ringtone {
            let loadingLogic = kCreateLoadingLogic {
                self.stateChangeBlock(.loading(0.0))
            } hideBlock: {
                self.stateChangeBlock(.loading(1.0))
            }

            loadingLogic.show()
            isStop = false
            TSCommonTool.downloadAndCacheFile(from: ringtone) { [weak self] path, error in
                guard let self = self else { return }
                loadingLogic.hide()
                
                if isStop == true{
                    self.stop()
                    return
                }
                
                if let path = path {
                    //播放
                    if let url = URL(string: path) {
                        self.audioPlayer = TSAudioPlayer(url: url)
                        self.audioPlayer?.setLoop(true)
                        setVolume(volume: 1.0)
                        self.play()
                        dePrint(self.audioPlayer?.duration)
                    }
                    
                }else{
                    //暂停
                    self.stop()
                }
            }
        }
    }
    
    
    func play() {
        self.audioPlayer?.play()
        stateChangeBlock(.play)
    }
    
    func stop() {
        isStop = true
        self.audioPlayer?.stop()
        stateChangeBlock(.stop)
    }
    
    func pause() {
        self.audioPlayer?.pause()
        stateChangeBlock(.pause)
    }
    
    func setVolume(volume:Float){
        self.audioPlayer?.setVolume(volume)
        stateChangeBlock(.volume(volume))
    }
    
    func changeAudioSwitch()->Float {
        let volume:Float = self.audioPlayer?.volume == 0.0 ? 1.0 : 0.0
        setVolume(volume: volume)
        return volume
    }
     
    deinit {
        dePrint("TSBusinessAudioPlayer deinit")
    }
}
