//
//  SpeakAIVideoPlayManager.swift
//  SpeakEasyLearnEnglish
//
//  Created by edy on 2025/8/18.
//

import UIKit

class SpeakAIVideoPlayManager: UIView {

    static let share = SpeakAIVideoPlayManager()
    
    private var backgoundAI = SpeakVideoPlayer()
    private var SpeakAI = SpeakVideoPlayer()
    
    private override init(frame: CGRect) {
        super.init(frame: frame)
        NotificationCenter.default.addObserver(self, selector: #selector(Foreground), name: UIApplication.willEnterForegroundNotification, object: nil)
        SpeakAI.PlayFinish = { [weak self] in
            self?.PlayBg()
        }
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    @objc private func Foreground() -> Void {
        PlayBg()
    }
    
    func loadVideo() -> Void {
        self.layer.sublayers?.forEach({$0.removeFromSuperlayer()})
        backgoundAI.loadVideo(state: .none)
        SpeakAI.loadVideo(state: .runloop)
        
        if let bg = backgoundAI.SpeakPlayerLayer,
           let ai = SpeakAI.SpeakPlayerLayer{
            self.layer.insertSublayer(bg, at: 10)
            self.layer.insertSublayer(ai, at: 15)
            Print("添加AI动画成功")
        }
    }
    
    func PlaySpeak(_ duration:Double) -> Void {
        
        SpeakAI.SpeakPlayerLayer?.zPosition = 15
        
        backgoundAI.SpeakPlayerLayer?.zPosition = 10
        backgoundAI.stop()
        
        let vduration = SpeakAI.duration
        let count = ceil(duration / vduration)
        let rate = (count*vduration)/duration
        SpeakAI.videoPlayer(rate, playCount: Int(count))
    }
    
    func PlayBg() -> Void {
        SpeakAI.SpeakPlayerLayer?.zPosition = 10
        SpeakAI.stop()
        
        backgoundAI.SpeakPlayerLayer?.zPosition = 15
        backgoundAI.play()
    }
    
    override func layoutSubviews() {
        super.layoutSubviews()
        self.layoutIfNeeded()
        SpeakAI.SpeakPlayerLayer?.frame = self.bounds
        backgoundAI.SpeakPlayerLayer?.frame = self.bounds
    }
    
    func stop() -> Void {
        SpeakAI.stop()
        backgoundAI.stop()
    }
    
}
