//
//  TSThemeBrowseVM.swift
//  AIRingtone
//
//  Created by 100Years on 2025/3/3.
//

class TSThemeBrowseVM {

    var audioPlayer: TSAudioPlayer?
    
    //vc 的 currentIndex 是根据滚动视图平凡变动的,finallyIndex只会在有新值时候产生变动
    var finallyIndex:Int = -1
    
    func playRingtone(ringtone:String?) {
        if let ringtone = ringtone {
            self.audioPlayer?.stop()
            TSCommonTool.downloadAndCacheFile(from: ringtone) { [self] path, error in
                if let path = path {
                    //播放
                    if let url = URL(string: path) {
                        self.audioPlayer = TSAudioPlayer(url: url)
                        self.audioPlayer?.setLoop(true)
                        self.audioPlayer?.setVolume(1.0)
                        self.audioPlayer?.play()
                        dePrint(self.audioPlayer?.duration)
                    }
                    
                }else{
                    //暂停
                    self.audioPlayer?.stop()
                }
            }
        }
    }
    
    func setFinallyIndex(_ currentIndex:Int,ringtone:String?)  {
        if finallyIndex != currentIndex{
            finallyIndex = currentIndex
            playRingtone(ringtone: ringtone)
        }
    }

    func changeAudioState()->Float {
        let volume:Float = self.audioPlayer?.volume == 0.0 ? 1.0 : 0.0
        self.audioPlayer?.setVolume(volume)
        return volume
    }
}
