//
//  SpeakVideoPlayer.swift
//  SpeakEasyLearnEnglish
//
//  Created by edy on 2025/7/7.
//

import UIKit
import AVFoundation

class SpeakVideoPlayer {
    
    var players:AVPlayer?
    var playerLayers:AVPlayerLayer?
    
    private var playCount:Int = 0
    private var currentPlay:Int = 0
    
    static let share = SpeakVideoPlayer()
    
    open func videoPlayer(_ rate:Double = 0 , playCount:Int = 0) -> Void {
        self.stop()
        self.playCount = playCount
        currentPlay = 0
        players?.play()
        DispatchQueue.main.asyncAfter(deadline: .now()+0.1) {
            self.players?.rate = Float(rate)
        }
    }
    
    private init() {
        let videos = ["职业女性"]
        var urls:[URL] = []
        for name in videos {
            if let path = Bundle.main.path(forResource: name, ofType: ".mp4") {
                let url = URL(fileURLWithPath: path)
                urls.append(url)
            }
        }
        self.setupPlayers(videoURLs: urls)
    }
    
    // 初始化多个视频播放器
    private func setupPlayers(videoURLs: [URL]) {
        // 为每个视频创建播放器
        for (_, url) in videoURLs.enumerated() {
            let playerItem = AVPlayerItem(url: url)
            
            let player = AVPlayer(playerItem: playerItem)
            players = player
            // 创建对应的图层
            let playerLayer = AVPlayerLayer(player: player)
            playerLayer.videoGravity = .resizeAspectFill
            playerLayer.shouldRasterize = true
            playerLayer.rasterizationScale = UIScreen.main.nativeScale
            playerLayers = playerLayer
            // 设置循环播放
            playerItem.preferredPeakBitRate = 1
            NotificationCenter.default.addObserver(
                forName: .AVPlayerItemDidPlayToEndTime,
                object: playerItem,
                queue: .main
            ) { [weak player] _ in
                if self.playCount > 0 {
                    self.currentPlay += 1
                    Print(self.currentPlay)
                    if self.currentPlay >= self.playCount {
                        player?.seek(to: .zero)
                        return
                    }
                    player?.seek(to: .zero)
                    player?.play()
                }else{
                    player?.seek(to: .zero)
                    player?.play()
                }
                
            }
        }
    }
    
    func play() {
        players?.play()
    }
    
    func pause() {
        players?.pause()
    }
    
    func stop() -> Void {
        players?.pause()
        players?.seek(to: .zero)
    }
    
    deinit {
        players?.pause()
        NotificationCenter.default.removeObserver(self)
    }
    
}
