//
//  TSAudioPlayerManager.swift
//  AIRingtone
//
//  Created by 100Years on 2025/3/18.
//

import AVFoundation
import Foundation


class TSURL:Equatable{
    static func == (lhs: TSURL, rhs: TSURL) -> Bool {
        if lhs.url == rhs.url,
           lhs.uuid == rhs.uuid {
            return true
        }
        return false
    }
    
    var uuid:String = UUID().uuidString
    var url:URL
    init(uuid: String, url: URL) {
        self.uuid = uuid
        self.url = url
    }
}

import AVFoundation
import Foundation

let kAudioAVPlayerShared = AudioAVPlayer.shared
class AudioAVPlayer: NSObject {
    // MARK: - Properties
    static let shared = AudioAVPlayer()
    private var player: AVPlayer?
    private var playerItem: AVPlayerItem?
    private var timeObserverToken: Any?
    
    // MARK: - Callbacks
    var onPlaybackProgress: ((Double) -> Void)? // 播放进度回调
    var onPlaybackStateChanged: ((PlaybackState) -> Void)? // 播放状态回调
    var onPlaybackFinished: (() -> Void)? // 播放完成回调
    
    // MARK: - Enums
    enum PlaybackState {
        case notStarted
        case loading(Double)
        case playing
        case playProgress(Double)
        case paused
        case finished
    }
    
    // MARK: - Initialization
    private override init() {
        super.init()
    }
    
    // MARK: - Public Methods
    /// 加载音频
    func loadAudio(from url: URL) {
        playerItem = AVPlayerItem(url: url)
        player = AVPlayer(playerItem: playerItem)
        player?.addObserver(self, forKeyPath: "status", options: .new, context: nil)
        addPeriodicTimeObserver()
        addPlayerItemObservers()
    }
    
    /// 播放音频
    func play() {
        player?.play()
        notifyPlaybackStateChanged(.playing)
    }
    
    /// 暂停音频
    func pause() {
        player?.pause()
        notifyPlaybackStateChanged(.paused)
    }
    
    /// 停止音频
    func stop() {
        player?.pause()
        player?.seek(to: CMTime.zero)
        notifyPlaybackStateChanged(.notStarted)
    }
    
    /// 跳转到指定时间
    func seek(to time: Double) {
        let cmTime = CMTime(seconds: time, preferredTimescale: 1)
        player?.seek(to: cmTime)
    }
    
    // MARK: - Private Methods
    /// 添加播放进度监听
    private func addPeriodicTimeObserver() {
        let interval = CMTime(seconds: 0.5, preferredTimescale: CMTimeScale(NSEC_PER_SEC))
        timeObserverToken = player?.addPeriodicTimeObserver(forInterval: interval, queue: .main) { [weak self] time in
            guard let self = self else { return }
            let currentTime = CMTimeGetSeconds(time)
            let duration = CMTimeGetSeconds(self.playerItem?.duration ?? CMTime.zero)
            let progress = duration > 0 ? currentTime / duration : 0
            self.onPlaybackProgress?(progress)
        }
    }
    
    /// 添加播放状态监听
    private func addPlayerItemObservers() {
        NotificationCenter.default.addObserver(self, selector: #selector(playerItemDidPlayToEndTime), name: .AVPlayerItemDidPlayToEndTime, object: playerItem)
    }
    
    /// 播放完成
    @objc private func playerItemDidPlayToEndTime() {
        notifyPlaybackStateChanged(.finished)
        onPlaybackFinished?()
    }
    
    /// 监听播放器状态
    override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
        if keyPath == "status", player?.status == .readyToPlay {
            notifyPlaybackStateChanged(.notStarted)
        }
    }
    
    /// 通知播放状态变化
    private func notifyPlaybackStateChanged(_ state: PlaybackState) {
        DispatchQueue.main.async {
            self.onPlaybackStateChanged?(state)
        }
    }
    
    // MARK: - Deinit
    deinit {
        player?.removeObserver(self, forKeyPath: "status")
        if let token = timeObserverToken {
            player?.removeTimeObserver(token)
        }
        NotificationCenter.default.removeObserver(self, name: .AVPlayerItemDidPlayToEndTime, object: playerItem)
    }
}

/*
 
 
 let audioURL = URL(string: "https://example.com/audio.mp3")!
 AudioPlayer.shared.loadAudio(from: audioURL)

 AudioPlayer.shared.onPlaybackStateChanged = { state in
     print("播放状态: \(state)")
 }

 AudioPlayer.shared.onPlaybackProgress = { progress in
     print("播放进度: \(progress)")
 }

 AudioPlayer.shared.onPlaybackFinished = {
     print("播放完成")
 }

 AudioPlayer.shared.play()
 
 */
