//
//  TSAudioPlayer.swift
//  Girly
//
//  Created by 100Years on 2025/1/9.
//

import AVFoundation

class TSAudioPlayer : NSObject, AVAudioPlayerDelegate{
    private var audioPlayer: AVAudioPlayer?
    var isLooping: Bool = false
    
    override init() {
        super.init()
    }
    
    var isPlaying:Bool{
        if let audioPlayer = audioPlayer {
            return audioPlayer.isPlaying
        }
        return false
    }
    
    var duration:Double{
        if let audioPlayer = audioPlayer {
            return audioPlayer.duration
        }
        return 0.0
    }
    
    var volume:Float{
        if let audioPlayer = audioPlayer {
            return audioPlayer.volume
        }
        return 0
    }
    
    //播放器是否可用
    var playerUsable:Bool {
        if audioPlayer != nil  {
            return true
        }
        return false
    }

    /// 初始化播放器
    /// - Parameter url: 音频文件的 URL
    init?(url: URL) {
        super.init()
        do {
            audioPlayer = try AVAudioPlayer(contentsOf: url)
            audioPlayer?.prepareToPlay()
            audioPlayer?.delegate = self
            let audioSession = AVAudioSession.sharedInstance()
            try audioSession.setCategory(.playback) // 设置类别为 playback
            try audioSession.setActive(true) // 激活音频会话

        } catch {
            print("音频文件加载失败: \(error.localizedDescription)")
            return nil
        }
    }
    
    /// 开始播放音频
    func play() {
        guard let audioPlayer = audioPlayer else { return }
        let outputVolume = AVAudioSession.sharedInstance().outputVolume
        dePrint("outputVolume\(outputVolume)")
        
        if outputVolume == 0.0 {
            TSToastShared.showToast(text: "Please turn up the volume".localized)
        }
    
        audioPlayer.numberOfLoops = isLooping ? -1 : 0
        audioPlayer.play()
    }
    
    /// 暂停播放音频
    func pause() {
        audioPlayer?.pause()
    }
    
    /// 停止并销毁播放器
    func stop() {
        audioPlayer?.stop()
        audioPlayer = nil
    }
    
    /// 设置是否重复播放
    /// - Parameter loop: 是否循环播放
    func setLoop(_ loop: Bool) {
        isLooping = loop
        audioPlayer?.numberOfLoops = loop ? -1 : 0
    }
    
    /// 设置音量
    /// - Parameter volume: 音量大小 (0.0 静音, 1.0 最大)
    func setVolume(_ volume: Float) {
        audioPlayer?.volume = max(0.0, min(volume, 1.0))
    }
    
    deinit {
        stop()
    }

    var audioPlayerDidFinishHandle:((Bool)->Void)?
    // 实现 AVAudioPlayerDelegate 方法
    func audioPlayerDidFinishPlaying(_ player: AVAudioPlayer, successfully flag: Bool) {
        if flag {
            print("音频播放完成")
            
        } else {
            print("音频播放中断")
        }
        audioPlayerDidFinishHandle?(flag)
    }
}
